-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathElectionWinner.java
More file actions
25 lines (22 loc) · 853 Bytes
/
ElectionWinner.java
File metadata and controls
25 lines (22 loc) · 853 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
import java.util.*;
public class ElectionWinner {
// Complete the electionWinner function below.
static String electionWinner(String[] votes) {
if(votes == null || votes.length == 0) {
return null;
}
HashMap<String, Integer> freqMap = new HashMap<>();
for(int i = 0; i < votes.length; i++) {
freqMap.put(votes[i], freqMap.getOrDefault(votes[i], 0) + 1);
}
int max = Integer.MIN_VALUE;
String res = "";
for(Map.Entry<String, Integer> entry : freqMap.entrySet()) {
if(entry.getValue() > max || entry.getValue() == max && entry.getKey().compareTo(res) > 0) { // !!!
max = entry.getValue() ;
res = entry.getKey();
}
}
return res;
}
}