Skip to content

Commit 55d07ff

Browse files
authored
Create 169. Majority Element.java
1 parent 317ed34 commit 55d07ff

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)