Skip to content

Commit 4b4c078

Browse files
committed
majority element in an array
1 parent fa76e58 commit 4b4c078

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

divideAndConquer/majorityElement.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
/*
3+
Majority element is that which occurs more than n/2 times.
4+
We start with assigning first element as majority and give it a count 1,
5+
we increase the count if we find the majority element else decrement,
6+
if count reaches 0, we make the current element major and count as 1.
7+
*/
8+
public int majorityElement(int[] nums) {
9+
int major = nums[0];
10+
int count = 1;
11+
for (int i =1; i<nums.length;i++) {
12+
if (count == 0) {
13+
count ++;
14+
major = nums[i];
15+
}
16+
17+
else if (major == nums[i]) {
18+
count ++;
19+
}
20+
21+
else {
22+
count --;
23+
}
24+
}
25+
return major;
26+
}
27+
}

0 commit comments

Comments
 (0)