Skip to content

Commit 67274ff

Browse files
committed
Time: 7 ms (97.55%), Space: 20.1 MB (7.34%) - LeetHub
1 parent 2ef3cea commit 67274ff

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
int majorityElement(vector<int>& nums) {
4+
// solving by using Boyer-Moore Majority Voting Algorithm
5+
int n = nums.size();
6+
int cnt = 0;
7+
int curIdx = 0;
8+
for (int i = 0; i < n; i++) {
9+
if(nums[i] != nums[curIdx]) {
10+
cnt--;
11+
} else {
12+
cnt++;
13+
}
14+
15+
if(cnt == 0) {
16+
curIdx = i;
17+
cnt++;
18+
}
19+
}
20+
21+
return nums[curIdx];
22+
}
23+
};

0 commit comments

Comments
 (0)