Skip to content

Commit 910bbd2

Browse files
authored
Create Majority Element
1 parent ac721ac commit 910bbd2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Majority Element

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.Arrays;
2+
3+
class Solution {
4+
public int majorityElement(int[] nums) {
5+
if(nums.length==1){
6+
return nums[0];
7+
}
8+
Arrays.sort(nums);
9+
int count = 1;
10+
int maxCount = 0;
11+
int result = 0;
12+
13+
for(int i = 0; i<nums.length-1;i++){
14+
if(nums[i] == nums[i+1]){
15+
count++;
16+
}
17+
if(nums[i] != nums[i+1]){
18+
if(maxCount <= count){
19+
maxCount = count;
20+
result = nums[i];
21+
22+
}
23+
count = 0;
24+
}
25+
26+
}
27+
28+
if(maxCount <= count){
29+
maxCount = count;
30+
result = nums[nums.length-1];
31+
32+
}
33+
return result;
34+
}
35+
}

0 commit comments

Comments
 (0)