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(lint i=l+1;//左端点,从基准值的下一个开始比较
        int j=r;//右端点
        while(iif(*(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; i2)
    {
        sum+=*(nums+i);
    }
    return sum;
}

你可能感兴趣的:(每日一题leetcode)