1. 程式人生 > >LeetCode 561. Array Partition I (數組分隔之一)

LeetCode 561. Array Partition I (數組分隔之一)

art 需要 style output tco code 個數字 num array

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:

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


題目標簽:Array

  這道題目給了我們一個數組有2n integers, 需要我們把這個數組分成n對,然後從每一對裏面拿小的那個數字,把所有的加起來,返回這個sum。並且要使這個sum 盡量最大。如何讓sum 最大化呢,我們想一下,如果是兩個數字,一個很小,一個很大,這樣的話,取一個小的數字,就浪費了那個大的數字。所以我們要使每一對的兩個數字盡可能接近。我們先把nums sort 一下,讓它從小到大排列,接著每次把index: 0, 2, 4...偶數位的數字加起來就可以了。

Java Solution:

Runtime beats 83.27%

完成日期:05/10/2017

關鍵詞:Array

關鍵點:Sort

 1 public class Solution 
 2 {
 3     public int arrayPairSum(int[] nums) 
 4     {
 5         int sum = 0;
 6         
 7         Arrays.sort(nums);
 8         
 9         for(int i=0; i<nums.length; i+=2)
10             sum += nums[i];
11         
12
return sum; 13 } 14 }

參考資料:N/A

LeetCode 561. Array Partition I (數組分隔之一)