561. Array Partition I(C语言)

这道题什么鬼

不应该输出5[2,3],一组,[1,4]一组么

Given an array of  2n integers, your task is to group these integers into  n pairs of integer, say (a 1, b 1), (a 2, b 2), ..., (a n, b n) which makes sum of min(a i, b i) 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:

  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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值