Skip to content

Commit e4c101b

Browse files
committed
LC#300, finds majority element in array, O(N) time, O(N) Space
1 parent 31b52be commit e4c101b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package easy;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class MajorityElement169 {
7+
8+
public static int majorityElement(int[] nums) {
9+
10+
HashMap<Integer, Integer> map = new HashMap<>();
11+
12+
for (int n : nums) {
13+
if (!map.containsKey(n)) {
14+
map.put(n, 1);
15+
} else {
16+
map.put(n, map.get(n) + 1);
17+
}
18+
}
19+
20+
double maxLimit = Math.ceil(nums.length / 2.0);
21+
int ans = Integer.MAX_VALUE;
22+
23+
for (Map.Entry<Integer, Integer> entries : map.entrySet()) {
24+
if (entries.getValue() >= maxLimit)
25+
ans = entries.getKey();
26+
}
27+
return ans;
28+
}
29+
30+
public static void main(String[] args) {
31+
int[] nums = { 2, 2, 1, 1, 1, 2, 2 };
32+
System.out.println(majorityElement(nums));
33+
34+
System.out.println(majorityElement(new int[] { 3, 2, 3 }));
35+
36+
System.out.println(majorityElement(new int[] { 2, 2 }));
37+
38+
}
39+
}

0 commit comments

Comments
Β (0)