您的位置:首页 > 编程语言 > C语言/C++

561. Array Partition I(C语言)

2017-05-10 11:03 597 查看
这道题什么鬼
不应该输出5,[2,3],一组,[1,4]一组么
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.


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].

这道题我又理解错题意了,还好柏宁晚饭时候,帮我讲了讲
这个min(ai,bi)的意思是(ai,bi)这个数对里最小的值ai或者bi,比如[1,3]里是1,[2,4]里是2

sum of min(ai,bi) from i to n的意思的是,所有1到n这n个数对里,相对较小的值的和

所以题目要求是:

1.求数对里的最小值

2.对所有数对的最小值求和

3.使这个和最大

解题方法就是:2n个数,从小到大排序,然后奇数下标相加

写了一个冒泡排序,超时,改成了快排,AC

int arrayPairSum(int* nums, int numsSize) {
int i=0,j=numsSize-1;
int sum=0;

void sort(int i,int j,int* nums);//函数声明
sort(0,numsSize-1, nums);
for(i=0;i<numsSize;i=i+2){
sum+=nums[i];
}

return sum;
}

void sort(int i,int j,int* nums){
int low=i;
int high=j;
int key=nums[i];
int temp=0;

if(i>j){
return ;
}
while(i<j){
while(nums[j]>key&&i<j){
j--;
}
nums[i]=nums[j];
while(nums[i]<=key&&i<j){
i++;

}
nums[j]=nums[i];

}

nums[i]=key;
sort(low,i-1,nums);
sort(i+1,high,nums);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: