-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path561.ArrayPartitionI.cpp
35 lines (33 loc) · 982 Bytes
/
561.ArrayPartitionI.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
vector<int> hashtable(20001,0);// if we don't know the range, wo could use multiset.
for(size_t i= 0;i<nums.size();i++){
hashtable[nums[i]+10000]++;
}
int ret = 0;
int flag = 0;
for(size_t i = 0;i<20001;){
if(hashtable[i]>0 && (flag ==0)){
ret = ret+i-10000;// flag = 0 mean this is the smaller num in a pair。
flag = 1;
hashtable[i]--;
}
else if(hashtable[i]>0&& (flag == 1)){
hashtable[i]--; // flag = 1 mean this is the larger num in a pair。
flag =0;
}
else
i++;
}
return ret;
}
};
//python solution
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])