Skip to content

Commit 0d96dcf

Browse files
committed
Majority element done
1 parent 26facf5 commit 0d96dcf

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.leetcode.arrays;
2+
3+
/**
4+
* Level: Easy
5+
* Problem Link: https://leetcode.com/problems/majority-element/
6+
* Problem Description:
7+
* Given an array of size n, find the majority element. The majority element is the element
8+
* that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the
9+
* majority element always exist in the array.
10+
*
11+
* @author rampatra
12+
* @since 2019-04-27
13+
*/
14+
public class MajorityElement {
15+
16+
/**
17+
* Time complexity: O(n)
18+
* Runtime: <a href="https://leetcode.com/submissions/detail/225284632/">1 ms</a>.
19+
*
20+
* @param nums
21+
* @return
22+
*/
23+
public static int majorityElement(int[] nums) {
24+
int count = 0;
25+
int majElem = nums[0];
26+
27+
for (int i = 0; i < nums.length; i++) {
28+
if (count <= 0) {
29+
majElem = nums[i];
30+
count = 0;
31+
}
32+
if (majElem == nums[i]) {
33+
count++;
34+
} else {
35+
count--;
36+
}
37+
}
38+
39+
return majElem;
40+
}
41+
42+
public static void main(String[] args) {
43+
System.out.println(majorityElement(new int[]{10, 9, 9, 9, 10}));
44+
System.out.println(majorityElement(new int[]{2, 3, 2, 2, 3, 2}));
45+
System.out.println(majorityElement(new int[]{2, 3, 2, 2, 2, 3}));
46+
}
47+
}

0 commit comments

Comments
 (0)