-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMajorityElement.java
More file actions
32 lines (30 loc) · 827 Bytes
/
MajorityElement.java
File metadata and controls
32 lines (30 loc) · 827 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package io.ziheng.hashtable.leetcode;
import java.util.Map;
import java.util.HashMap;
/**
* LeetCode 169. Majority Element
* https://leetcode.com/problems/majority-element/
*/
public class MajorityElement {
public int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
map.put(num, 1 + map.get(num));
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > n / 2) {
return entry.getKey();
}
}
return -1;
}
}
/* EOF */