File tree Expand file tree Collapse file tree 1 file changed +17
-12
lines changed
0501-1000/0561-Array-Partition-I/cpp-0561 Expand file tree Collapse file tree 1 file changed +17
-12
lines changed Original file line number Diff line number Diff line change 1
1
// / Source : https://leetcode.com/problems/array-partition-i/solution/
2
2
// / Author : liuyubobobo
3
3
// / Time : 2018-06-04
4
+ // / Updated: 2022-06-15
4
5
5
6
#include < iostream>
6
7
#include < vector>
7
8
8
9
using namespace std ;
9
10
10
- // / Using HashMap
11
- // / Time Complexity: O(n)
12
- // / Space Complexity: O(n)
11
+
12
+ // / Counting Sort based
13
+ // / Time Complexity: O(n + (maxv - minv))
14
+ // / Space Complexity: O(maxv - minv)
13
15
class Solution {
14
16
public:
15
17
int arrayPairSum (vector<int >& nums) {
16
18
17
- int hash[20001 ];
18
- memset (hash, 0 , sizeof (hash));
19
+ int maxv = *max_element (nums.begin (), nums.end ());
20
+ int minv = *min_element (nums.begin (), nums.end ());
21
+
22
+ vector<int > cnt (maxv - minv + 2 , 0 );
23
+ int offset = -minv;
19
24
20
25
for (int num: nums)
21
- hash [num + 10000 ] ++;
26
+ cnt [num + offset ] ++;
22
27
23
28
int sum = 0 ;
24
29
bool minus = false ;
25
- for (int i = 0 ; i <= 20000 ; i ++)
26
- if (hash [i]){
30
+ for (int i = 0 ; i < cnt. size () ; i ++)
31
+ if (cnt [i]){
27
32
if (minus){
28
- hash [i] --;
33
+ cnt [i] --;
29
34
minus = false ;
30
35
}
31
- sum += hash [i] / 2 * (i - 10000 );
32
- if (hash [i] % 2 ){
33
- sum += (i - 10000 );
36
+ sum += cnt [i] / 2 * (i - offset );
37
+ if (cnt [i] % 2 ){
38
+ sum += (i - offset );
34
39
minus = true ;
35
40
}
36
41
}
You can’t perform that action at this time.
0 commit comments