Skip to content

Commit a2f4d40

Browse files
Create 57 58 59 60 61 Majority Element.java
1 parent b936036 commit a2f4d40

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//O(n) and O(1)
2+
class Solution {
3+
public int majorityElement(int[] nums) {
4+
if(nums==null || nums.length==0) return 0;
5+
int maj = nums[0],count=1;
6+
for(int i=1;i<nums.length;i++){
7+
if(nums[i]==maj)
8+
count++;
9+
else{
10+
count--;
11+
if(count==0){
12+
maj = nums[i];
13+
count = 1;
14+
}
15+
}
16+
}
17+
return maj;
18+
}
19+
}

0 commit comments

Comments
 (0)