leetcode 561. Array Partition I(C语言)10
2017-09-22 14:23
260 查看
贴原题:
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].
解析
本题我用了刚刚做另一道题时http://blog.csdn.net/m0_37454852/article/details/78062299 写的快速排序算法,就很简单了,排好序之后每隔一个相加就行了。
贴代码:
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].
解析
本题我用了刚刚做另一道题时http://blog.csdn.net/m0_37454852/article/details/78062299 写的快速排序算法,就很简单了,排好序之后每隔一个相加就行了。
贴代码:
void my_qsort(int* nums, int l, int r) { if(l<r) { int i=l+1;//左端点,从基准值的下一个开始比较 int j=r;//右端点 while(i<j) { if(*(nums+i)>*(nums+l))//若比关键值大,则把该值放到右端点(交换该值与右端点值) { int temp=*(nums+j); *(nums+j)=*(nums+i); *(nums+i)=temp; j--;//右端点右移 } else//否则就选择下一个继续比较 { i++; } } if(*(nums+i)>=*(nums+l)) { i--; } int temp=*(nums+i); *(nums+i)=*(nums+l); *(nums+l)=temp; my_qsort(nums, l, i-1);//递归调用 my_qsort(nums, i+1, r); } } int arrayPairSum(int* nums, int numsSize) { my_qsort(nums, 0, numsSize-1); int sum=0; for(int i=0; i<numsSize; i+=2) { sum+=*(nums+i); } return sum; }
相关文章推荐
- 【Leetcode】561. Array Partition I(数组分割一)
- leetcode 349. Intersection of Two Arrays(C语言)10
- Leetcode 561. Array Partition I(Easy)
- leetcode_561. Array Partition I ? 待解决
- LeetCode 561. Array Partition I
- LeetCode-561. Array Partition I-排序
- LeetCode | 561. Array Partition I 数学归纳法题
- leetcode -- 561. Array Partition I 【贪心算法 + 正确性证明】
- 10--LeetCode【Single Number】|C语言|
- 561. Array Partition I(C语言)
- [Leetcode] 561. Array Partition I 解题报告
- leetcode 557. Reverse Words in a String III(C语言)10
- leetcode 561. Array Partition I 数组元素分组的最小值的和的最大值+直接排序即可
- [LeetCode]561. Array Partition I (数组分区 1)
- LeetCode——561. Array Partition I(贪心,C++)
- 《C语言名题精选百则----10》
- LeetCode-19-Remove Nth Node From End of List(C语言实现)
- leetcode 463. Island Perimeter(C语言,二维数组,周长)23
- 数制转换,将10进制转换为8进制 C语言 栈的应用
- LeetCode - 10 - Regular Expression Matching