//O(nlogn)
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int n = nums.size(), ans = 0;
if (n % 2 != 0) return 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i += 2) {
ans += min(nums[i], nums[i + 1]);
}
return ans;
}
};
?Method 2: 计数排序,用空间换时间,避免了排序时间,从O(nlogn)降到O(n)
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
const int MaxValue = 10000;
array<int, 2 * MaxValue+1> count{};
//count数组size是数字区间的两倍,用来存放一个数字出现的个数,初始置为0
for (int num:nums) ++count[num+MaxValue];
int ans = 0;
bool first = true;
int n = 0; // n属于(-10000,10000)
while(n<count.size()){
if (!count[n]) { ++n;continue;} // 如果没有n在测试数组中出现过,就判断下一个
if (first) {
ans += (n-MaxValue);
first = false;
} else {first = true;}
--count[n];
}
return ans;
}
};