|
1 | 1 | class Solution {
|
2 | 2 | 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); |
11 | 10 | }
|
12 | 11 | }
|
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; |
20 | 17 | }
|
21 |
| - return c1 - c2; |
22 | 18 | }
|
| 19 | + return o1 - o2; |
23 | 20 | });
|
24 |
| - for (char c : votes[0].toCharArray()) { |
25 |
| - pq.add(c); |
26 |
| - } |
| 21 | + priorityQueue.addAll(map.keySet()); |
27 | 22 | StringBuilder sb = new StringBuilder();
|
28 |
| - while (!pq.isEmpty()) { |
29 |
| - sb.append(pq.poll()); |
| 23 | + while (!priorityQueue.isEmpty()) { |
| 24 | + sb.append(priorityQueue.poll()); |
30 | 25 | }
|
31 | 26 | return sb.toString();
|
32 | 27 | }
|
|
0 commit comments