1. 程式人生 > >561. Array Partition I - LeetCode

561. Array Partition I - LeetCode

class urn src scrip problems 相加 arr for pair

Question

561. Array Partition I

技術分享圖片

Solution

題目大意是,給的數組大小是2n,把數組分成n組,每組2個元素,每個組取最小值,這樣就能得到n個值,怎樣分組才能使這n個數相加最小。

思路:有點田忌賽馬的意思,肯定最大和第二大一組,取最小值即第二大的數,依次類推。。。這樣就需要排序,隔一個取一個。

Java實現:

public int arrayPairSum(int[] nums) {
    Arrays.sort(nums);
    int total = 0;
    for (int i=0; i<nums.length; i+=2) {
        total += nums[i];
    }
    return
total; }

561. Array Partition I - LeetCode