1
+ // Runtime: 775 ms (Top 27.44%) | Memory: 140.3 MB (Top 88.77%)
1
2
class Solution {
2
3
public:
3
4
int minimumOperations (vector<int >& nums) {
4
-
5
+
5
6
int totalEven = 0 , totalOdd = 0 ;
6
-
7
+
7
8
unordered_map<int ,int > mapEven, mapOdd;
8
-
9
+
9
10
for (int i=0 ;i<nums.size ();i++) {
10
11
if (i%2 ==0 ) {
11
12
totalEven++;
12
13
mapEven[nums[i]]++;
13
14
}
14
-
15
+
15
16
else {
16
17
totalOdd++;
17
18
mapOdd[nums[i]]++;
18
19
}
19
20
}
20
-
21
-
21
+
22
22
int firstEvenCount = 0 , firstEven = 0 ;
23
23
int secondEvenCount = 0 , secondEven = 0 ;
24
-
24
+
25
25
for (auto it=mapEven.begin ();it!=mapEven.end ();it++) {
26
26
int num = it->first ;
27
27
int count = it->second ;
28
-
28
+
29
29
if (count>=firstEvenCount) {
30
30
secondEvenCount = firstEvenCount;
31
31
secondEven = firstEven;
32
32
firstEvenCount = count;
33
33
firstEven = num;
34
34
}
35
-
35
+
36
36
else if (count >= secondEvenCount) {
37
37
secondEvenCount = count;
38
38
secondEven = num;
39
39
}
40
40
}
41
-
42
-
41
+
43
42
int firstOddCount = 0 , firstOdd = 0 ;
44
43
int secondOddCount = 0 , secondOdd = 0 ;
45
-
46
-
44
+
47
45
for (auto it=mapOdd.begin ();it!=mapOdd.end ();it++) {
48
46
int num = it->first ;
49
47
int count = it->second ;
50
-
48
+
51
49
if (count>=firstOddCount) {
52
50
secondOddCount = firstOddCount;
53
51
secondOdd = firstOdd;
54
52
firstOddCount = count;
55
53
firstOdd = num;
56
54
}
57
-
55
+
58
56
else if (count>=secondOddCount) {
59
57
secondOddCount = count;
60
58
secondOdd = num;
61
59
}
62
60
}
63
-
61
+
64
62
int operationsEven = 0 , operationsOdd = 0 ;
65
-
66
-
63
+
67
64
operationsEven = totalEven - firstEvenCount;
68
-
65
+
69
66
if (firstEven!=firstOdd) operationsEven += (totalOdd - firstOddCount);
70
67
else operationsEven += (totalOdd - secondOddCount);
71
-
72
-
68
+
73
69
operationsOdd = totalOdd - firstOddCount;
74
70
if (firstOdd!=firstEven) operationsOdd += (totalEven - firstEvenCount);
75
71
else operationsOdd += (totalEven - secondEvenCount);
76
-
77
-
72
+
78
73
return min (operationsEven, operationsOdd);
79
-
74
+
80
75
}
81
- };
76
+ };
0 commit comments