贪婪的做法,每一次取一对之后,我们能给结果加上最大的数就是第二大的数。因为最大的数我们肯定是取不到的。这样我们每次取的数实际上就是sorted之后index为偶数的数。时间复杂度O(n * log n),常数空间,代码如下:
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 res = 0; | |
for(int i = 0; i < nums.size(); i += 2) | |
res += nums[i]; | |
return res; | |
} | |
}; |
No comments:
Post a Comment