Skip to content

Commit 1eee345

Browse files
committed
Create majority-element.cpp
1 parent c067d6d commit 1eee345

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

C++/majority-element.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int majorityElement(vector<int>& nums) {
7+
int ans = nums[0], cnt = 1;
8+
for (const auto& i : nums) {
9+
if (i == ans) {
10+
++cnt;
11+
} else {
12+
--cnt;
13+
if (cnt == 0) {
14+
ans = i;
15+
cnt = 1;
16+
}
17+
}
18+
}
19+
return ans;
20+
}
21+
};

0 commit comments

Comments
 (0)