Skip to content

Commit 6df5759

Browse files
committed
refactor: top-k-frequent-elements solution
1 parent 23984e6 commit 6df5759

File tree

1 file changed

+6
-12
lines changed

1 file changed

+6
-12
lines changed

top-k-frequent-elements/sm9171.java

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,20 @@
11
class Solution {
2-
public int[] topKFrequent(int[] nums, int k) {
2+
public static int[] topKFrequent(int[] nums, int k) {
33
Map<Integer, Integer> hashMap = new HashMap<>();
44
for (int i = 0; i < nums.length; i++) {
55
int num = nums[i];
6-
if (hashMap.containsKey(num)) {
7-
hashMap.put(num, hashMap.get(num) + 1);
8-
continue;
9-
}
10-
hashMap.put(num, 1);
6+
hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
117
}
128

13-
List<Integer> list = hashMap.entrySet()
14-
.stream()
9+
List<Integer> list = hashMap.entrySet().stream()
1510
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
1611
.limit(k)
1712
.map(Map.Entry::getKey)
1813
.toList();
1914

20-
int [] result = new int[list.size()];
21-
for (int i = 0; i < list.size(); i++) {
22-
result[i] = list.get(i);
23-
}
15+
int[] result = list.stream()
16+
.mapToInt(Integer::intValue)
17+
.toArray();
2418

2519
return result;
2620
}

0 commit comments

Comments
 (0)