561.數組拆分

原文鏈接:https://leetcode-cn.com/problems/array-partition-i/

 

題目:

思路分析:這道題是給定一個長度爲2n的數組,然後我們將這些數分成n對,

1.將數組元素進行升序排序。

2.遍歷數組,將角標爲偶數的數組元素進行累加。

3.最後返回累加的結果。

源代碼:

class Solution {
    public int arrayPairSum(int[] nums) {
        //insertSort(nums);
        Arrays.sort(nums);
        int sum = 0;
        for(int i = 0;i < nums.length;i+=2){
            sum+=nums[i];
        }
        return sum;
    }
    public static int[] insertSort(int[] nums){
        int e;
        int j;
        for(int i = 1;i < nums.length;i++){
            e = nums[i];
            for(j = i;j > 0 && nums[j - 1] > e;j--){
                nums[j] = nums[j - 1];
            }
            nums[j] = e;
        }
        return nums;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章