【题目概要】 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: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000].
【思路分析】
目的使得分组后,每一组中的小值的和最大,则需要最小值最大按照从小到大排序,顺序选择相邻的两个数为一组【代码示例1】
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void quicksort(int *nums, int start, int end) { if(start >= end) { return; } int i = start; int j = end; int middle = (start+end)/2; if(nums[start] > nums[end]) swap(&nums[start], &nums[end]); if(nums[middle] > nums[end]) swap(&nums[middle], &nums[end]); if(nums[start] < nums[middle]) swap(&nums[start], &nums[middle]); int key = nums[start]; while(i < j) { while(i<j && nums[j] >= key) { j--; } nums[i] = nums[j]; while(i<j && nums[i] <= key) { i++; } nums[j] = nums[i]; } nums[i] = key; quicksort(nums, start, i-1); quicksort(nums, i+1, end); } int arrayPairSum(int* nums, int numsSize){ quicksort(nums, 0, numsSize-1); int re = 0; for(int i=0; i<numsSize; i=i+2) { re += nums[i]; } return re; } 【说明】利用快排的优化算法,3位数取中法确定枢轴,减少交换次数【代码示例2】
int cmp(const void *a, const void *b) { return *((int*)a) - *((int*)b); } int arrayPairSum(int* nums, int numsSize){ if(numsSize <= 0) return 0; int sum = 0; int index = 0; qsort(nums, numsSize, sizeof(int), cmp); while(index < numsSize) { sum += nums[index]; index += 2; } return sum; }