-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathMajority Element.java
More file actions
44 lines (35 loc) · 939 Bytes
/
Majority Element.java
File metadata and controls
44 lines (35 loc) · 939 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
33
34
35
36
37
38
39
40
41
42
43
44
//brute
import java.util.HashMap;
import java.util.Map;
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
// Early exit since majority is guaranteed
if (freqMap.get(num) > nums.length / 2) {
return num;
}
}
// Majority is guaranteed, so this line is technically unreachable
return -1;
}
}
//optimized
class Solution {
public int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
if (num == candidate) {
count++;
} else {
count--;
}
}
return candidate;
}
}