We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent fa76e58 commit 4b4c078Copy full SHA for 4b4c078
divideAndConquer/majorityElement.java
@@ -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
19
20
21
+ else {
22
+ count --;
23
24
25
+ return major;
26
27
+}
0 commit comments