BiruLyu
7/5/2017 - 10:45 PM

561. Array Partition I(1st).java

public class Solution {
    public int arrayPairSum(int[] nums) {
        if (nums == null || nums.length < 1) return 0;
        Arrays.sort(nums);
        int res = 0;
        for (int i = 0; i < nums.length; i += 2) {
            res += nums[i];
        }
        return res;
    }
}
public class Solution {
    public int arrayPairSum(int[] nums) {
        int[] buckets = new int[20001];
        for (int x = 0; x < nums.length; x++) {
            buckets[nums[x] + 10000]++;
        }
        boolean add = true;
        int sum = 0;
        for (int x = 0; x < buckets.length; x++) {
            int freq = buckets[x];
            while (freq != 0) {
                sum += add ? (x - 10000) : 0;
                freq--;
                add = !add;
            }
        }
        return sum;
    }
}