Skip to content

Commit 328a063

Browse files
authored
Update Rank Teams by Votes.java
1 parent 274ebd7 commit 328a063

File tree

1 file changed

+16
-21
lines changed

1 file changed

+16
-21
lines changed

Medium/Rank Teams by Votes.java

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,27 @@
11
class Solution {
22
public String rankTeams(String[] votes) {
3-
Map<Character, int[]> map = new HashMap<>();
4-
int n = votes[0].length();
5-
for(String vote : votes) {
6-
for (int i = 0; i < n; i++) {
7-
if (!map.containsKey(vote.charAt(i))) {
8-
map.put(vote.charAt(i), new int[n]);
9-
}
10-
map.get(vote.charAt(i))[i]++;
3+
Map<Character, Map<Integer, Integer>> map = new HashMap<>();
4+
int positionCount = votes[0].length();
5+
for (String vote : votes) {
6+
for (int i = 0; i < vote.length(); i++) {
7+
char c = vote.charAt(i);
8+
map.computeIfAbsent(c, k -> new HashMap<>());
9+
map.get(c).put(i, map.get(c).getOrDefault(i, 0) + 1);
1110
}
1211
}
13-
PriorityQueue<Character> pq = new PriorityQueue<>(new Comparator<Character>(){
14-
public int compare(Character c1, Character c2) {
15-
for (int i = 0; i < n; i++) {
16-
int c = map.get(c2)[i] - map.get(c1)[i];
17-
if (c != 0) {
18-
return c;
19-
}
12+
PriorityQueue<Character> priorityQueue = new PriorityQueue<>((o1, o2) -> {
13+
for (int i = 0; i < positionCount; i++) {
14+
int c = map.get(o2).getOrDefault(i, 0) - map.get(o1).getOrDefault(i, 0);
15+
if (c != 0) {
16+
return c;
2017
}
21-
return c1 - c2;
2218
}
19+
return o1 - o2;
2320
});
24-
for (char c : votes[0].toCharArray()) {
25-
pq.add(c);
26-
}
21+
priorityQueue.addAll(map.keySet());
2722
StringBuilder sb = new StringBuilder();
28-
while (!pq.isEmpty()) {
29-
sb.append(pq.poll());
23+
while (!priorityQueue.isEmpty()) {
24+
sb.append(priorityQueue.poll());
3025
}
3126
return sb.toString();
3227
}

0 commit comments

Comments
 (0)