leetcode 561. Array Partition I(C语言)10

贴原题:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值