Minimum Operations to Make the Array Alternating LeetCode solution in C++

1
class Solution {
2
public:
3
int minimumOperations(vector<int> &nums) {
4
int totalEven = 0, totalOdd = 0;
5

6
unordered_map<int, int> mapEven, mapOdd;
7

8
for (int i = 0; i < nums.size(); i++) {
9
if (i % 2 == 0) {
10
totalEven++;
11
mapEven[nums[i]]++;
12
}
13

14
else {
15
totalOdd++;
16
mapOdd[nums[i]]++;
17
}
18
}
19

20
int firstEvenCount = 0, firstEven = 0;
21
int secondEvenCount = 0, secondEven = 0;
22

23
for (auto it = mapEven.begin(); it != mapEven.end(); it++) {
24
int num = it->first;
25
int count = it->second;
26

27
if (count >= firstEvenCount) {
28
secondEvenCount = firstEvenCount;
29
secondEven = firstEven;
30
firstEvenCount = count;
31
firstEven = num;
32
}
33

34
else if (count >= secondEvenCount) {
35
secondEvenCount = count;
36
secondEven = num;
37
}
38
}
39

40
int firstOddCount = 0, firstOdd = 0;
41
int secondOddCount = 0, secondOdd = 0;
42

43
for (auto it = mapOdd.begin(); it != mapOdd.end(); it++) {
44
int num = it->first;
45
int count = it->second;
46

47
if (count >= firstOddCount) {
48
secondOddCount = firstOddCount;
49
secondOdd = firstOdd;
50
firstOddCount = count;
51
firstOdd = num;
52
}
53

54
else if (count >= secondOddCount) {
55
secondOddCount = count;
56
secondOdd = num;
57
}
58
}
59

60
int operationsEven = 0, operationsOdd = 0;
61

62
operationsEven = totalEven - firstEvenCount;
63

64
if (firstEven != firstOdd)
65
operationsEven += (totalOdd - firstOddCount);
66
else
67
operationsEven += (totalOdd - secondOddCount);
68

69
operationsOdd = totalOdd - firstOddCount;
70
if (firstOdd != firstEven)
71
operationsOdd += (totalEven - firstEvenCount);
72
else
73
operationsOdd += (totalEven - secondEvenCount);
74

75
return min(operationsEven, operationsOdd);
76
}
77
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0