Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ea80d1e

Browse files
solves majority element in java
1 parent af9661e commit ea80d1e

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

src/MajorityElement.java

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
1-
import java.util.HashMap;
2-
import java.util.Map;
1+
// https://leetcode.com/problems/majority-element
2+
// T: O(N)
3+
// S: O(1)
34

45
public class MajorityElement {
5-
public int majorityElement(int[] array) {
6-
Map<Integer, Integer> frequencies = getFrequencies(array);
7-
int maxFrequency = frequencies.values().stream().max(Integer::compareTo).get();
8-
for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
9-
if (entry.getValue() == maxFrequency) {
10-
return entry.getKey();
11-
}
12-
}
6+
public int majorityElement(int[] nums) {
7+
int candidate = nums[0], frequency = 0;
138

14-
return -1;
15-
}
9+
for (int element : nums) {
10+
frequency += element == candidate ? 1 : -1;
1611

17-
private static Map<Integer, Integer> getFrequencies(int[] array) {
18-
Map<Integer, Integer> result = new HashMap<>();
19-
for (int element : array) {
20-
result.put(element, result.getOrDefault(element, 0) + 1);
12+
if (frequency == 0) {
13+
candidate = element;
14+
frequency = 1;
15+
}
2116
}
22-
return result;
17+
18+
return candidate;
2319
}
2420
}

0 commit comments

Comments
 (0)