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].
想法如下
- 先把 array 做排序,然後將在奇數位置的數字加起來,就會是答案了。例如 [1,15, 6,3,8,9],排序後變成 [1,3,6,8,9,15],答案就會是 min(1,3) + min(6,8) + min(9,15) = 1 + 6 + 9,也就是在位置1,3,5的數字的總和
C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int arrayPairSum(vector<int>& nums) { | |
sort(nums.begin(), nums.end()); | |
int ans = 0; | |
const int len = nums.size(); | |
for(int i = 0; i < len; i += 2) { | |
ans += nums[i]; | |
} | |
return ans; | |
} | |
}; |
另一種想法是
- 因為題目有說數字的範圍,以及總數的範圍,所以可以先用一個 array 來儲存數字,每一個數都先加上 10000,這樣就會按照大小順序(0 - 20000)的方式存在 array,就可以省掉排序的時間
- 存到 array 之後,歷遍這個 array,如果某個 index 的值不為零,去檢查是不是奇數位的數字,是的話就加到答案,其 index - 10000 就是原本的值;如果不是的話,標注消耗過了即可
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int arrayPairSum(int[] nums) { | |
int[] table = new int[20001]; | |
for(int i = 0; i < nums.length; i++) { | |
table[nums[i] + 10000]++; | |
} | |
int ans = 0; | |
boolean isOdd = true; | |
for(int i = 0; i < 20001; i++) { | |
while(table[i] > 0) { | |
if(isOdd == true) { | |
ans += i - 10000; | |
} | |
isOdd = !isOdd; | |
table[i]--; | |
} | |
} | |
return ans; | |
} | |
} |
沒有留言:
張貼留言