561. Array Partition I (數組分組)

Given an array of 2n integers, your task is to groupthese integers into n pairsof integer, say (a1, b1), (a2, b2),..., (an, bn) which makes sum of min(ai, bi) forall i from 1 to n as large as possible.

Example1:
 

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



 

這個題目的意思就是給你一個偶數項的數組,然後把兩個數分一組,找出每組中最下的數,然後把這些最小的數加起來,還要讓總和儘可能的大.

其實稍微想一想就會發現,想要總和最大,就把數組排好續之後,每兩個連續的分一組,然後把每組中的第一個元素全部累加起來就好了,

實際上就是把數組中從下標爲0的元素開始的所有偶數下標都加在一起就是最大的了,如果找最小的和,就把數組排好序以後把前半部分元素加在一起就是最小的和了.


具體操作就分這兩個步驟:

1.給數組排序

2.累加偶數項和

代碼如下:


 

int arrayPairSum(int* nums, intnumsSize) {

    int sum=0;

    int i,t,p;

    for (i =1; i <numsSize; ++i)

    {

       t=nums[i];

       p=i-1;

       while(p>=0 && t<nums[p])

        {

           nums[p+1]=nums[p];

           p--;

        }

       nums[p+1]=t;

    }

   for(i=0;i<numsSize;i=i+2)

        sum+= nums[i];

    return sum;

}

最開始我用的冒泡排序,沒有通過,後來用了選擇排序,

發佈了39 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章