Skip to content

Commit 3b9d52b

Browse files
authored
Majority element
1 parent 1424caa commit 3b9d52b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ans/MajorityElement169.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Given an array nums of size n, return the majority element.
2+
3+
The majority element is the element that appears more thann / 2times. You may assume that the majority element always exists in the array
4+
5+
class Solution {
6+
public int majorityElement(int[] nums) {
7+
8+
9+
int prev=nums[0];
10+
int count=1;
11+
for(int i=1;i<nums.length;i++)
12+
{
13+
int curr=nums[i];
14+
if(curr!=prev)
15+
{
16+
if(count==0)
17+
18+
{
19+
prev=curr;
20+
count++;
21+
}
22+
23+
else
24+
{
25+
count--;
26+
}
27+
28+
}
29+
else
30+
{
31+
count++;
32+
}
33+
34+
}
35+
36+
37+
return prev;
38+
39+
40+
}
41+
}

0 commit comments

Comments
 (0)