561. Array Partition I(C语言)

来源:互联网 发布:淘宝的港版beats能买吗 编辑:程序博客网 时间:2024/06/06 03:50

这道题什么鬼

不应该输出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: 4Explanation: n is 2, and the maximum sum of pairs is 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].


这道题我又理解错题意了,还好柏宁晚饭时候,帮我讲了讲

这个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);    }


0 0
原创粉丝点击