Majority Element LeetCode solution in C++

1
class Solution {
2
public:
3
int majorityElement(vector<int> &nums) {
4
// Initialize sol and cnt to store the solution and its frequency for
5
// respective iterations...
6
int sol = 0, cnt = 0;
7
// For every element i in the array...
8
for (int i = 0; i < nums.size(); i++) {
9
// If cnt is equal to zero, update sol as sol = i
10
if (cnt == 0) {
11
sol = nums[i];
12
cnt = 1;
13
}
14
// If i is equal to candidate, increment cnt...
15
else if (sol == nums[i]) {
16
cnt++;
17
}
18
// Otherwise, decrement cnt...
19
else {
20
cnt--;
21
}
22
}
23
// Return & print the solution...
24
return sol;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0