Leetcode 561:Array Partition I

題目描述:https://leetcode.com/problems/array-partition-i

思想是讓值最接近的兩個數成爲一個group,最簡單的可以先排序,在取其中下標爲偶數的元素。但排序本身耗費時間。

可以先計算每個元素出現的次數,從小到大,每間隔一個元素取一個,相加。

AC代碼:

public class Solution {
    public int arrayPairSum(int[] nums) {
        int[] eles = new int[20001];
        for(int i=0; i<nums.length; i++){
            eles[nums[i] + 10000]++;
        }
        
        boolean check = true;
        int sum = 0;
        for(int i=0; i<eles.length; i++){
            while(eles[i] > 0){
                if(check){
                    sum += i-10000;
                }
                check = !check;
                eles[i]--;
            }
        }
        return sum;
    }
}


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