【easy】561. Array Partition I

 

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

 

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].
class Solution {
public:
    void quicksort(vector<int>& nums, int start, int end){//快排!!!
        int i = start;
        int j = end;
        int x = nums[i];
        if (start < end){
            while (i<j)
            {
                while (nums[j]<x && i<j)
                    j--;
                if (i<j)
                    nums[i++] = nums[j];
                while (nums[i]>x && i<j)
                    i++;
                if (i<j)
                    nums[j--] = nums[i];
            }
            nums[i] = x;
            quicksort(nums, start, i-1);
            quicksort(nums, i+1, end);
        }
    }
public:
    int arrayPairSum(vector<int>& nums) {
        //直接冒泡排序是超时的,所以考虑选择一个效率更高的排序
        int len = nums.size();
        quicksort(nums,0,len-1);
        //贪心策略:排序选择偶数下标,相加
        int sum = 0;
        for (int i=1;i<len;i+=2){
            sum += nums[i];
        }
        return sum;
    }
};
 

 

posted @ 2018-01-22 20:44  Sherry_Yang  阅读(94)  评论(0编辑  收藏  举报