-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMajorityElement.java
More file actions
55 lines (46 loc) · 1.64 KB
/
Copy pathMajorityElement.java
File metadata and controls
55 lines (46 loc) · 1.64 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Given an array of size n, find the majority element. The majority element is the element that appears
// more than ⌊ n/2 ⌋ times.
// You may assume that the array is non-empty and the majority element always exist in the array.
// See: https://leetcode.com/problems/majority-element/
// See: https://leetcode.com/explore/featured/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3321/
package leetcode.array_and_hashtable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class MajorityElement {
/**
* Sort solution. Actually this is faster than the HashMap solution although the
* worst O(n.log(n) time).
*/
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
/**
* One pass HashMap solution, O(n) time, O(n) space.
*/
public int majorityElement_var2(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
int count = countMap.getOrDefault(num, 0) + 1;
if ( count > nums.length / 2) {
return num;
} else {
countMap.put(num, count);
}
}
return -1;
}
/**
* Initial solution, O(n) time, O(n) space.
*/
public int majorityElement_var1(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums)
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
for (int num : countMap.keySet())
if (countMap.get(num) > nums.length / 2)
return num;
return -1;
}
}