Skip to content

Commit d2d0e7d

Browse files
committed
Top K Frequent Elements
1 parent 096914a commit d2d0e7d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Runtime: 10 ms(Beats: 95.83 %)
3+
Time Complexity: O(nlogn)
4+
- map에 item 추가 : O(n)
5+
- items 배열 정렬 : O(nlogn)
6+
- result 배열에 원소 추가 : O(n)
7+
8+
Memory: 49.50 MB(Beats: 6.84 %)
9+
Space Complexity: O(n)
10+
- map : O(n)
11+
- items : O(n)
12+
- result : O(n)
13+
*/
14+
15+
class Solution {
16+
class Item {
17+
int val;
18+
int cnt;
19+
20+
public Item(int val, int cnt) {
21+
this.val = val;
22+
this.cnt = cnt;
23+
}
24+
25+
public void plusOne() {
26+
this.cnt += 1;
27+
}
28+
}
29+
30+
public int[] topKFrequent(int[] nums, int k) {
31+
Map<Integer, Item> map = new HashMap<>();
32+
for (int num : nums) {
33+
Item item = map.get(num);
34+
if (item == null) {
35+
item = new Item(num, 1);
36+
map.put(num, item);
37+
} else {
38+
item.plusOne();
39+
}
40+
}
41+
42+
ArrayList<Item> items = new ArrayList<>(map.values());
43+
Collections.sort(items, (item1, item2) -> Integer.compare(item2.cnt, item1.cnt));
44+
45+
int[] result = new int[k];
46+
for (int i = 0; i < k; i++) {
47+
result[i] = items.get(i).val;
48+
}
49+
50+
return result;
51+
}
52+
}

0 commit comments

Comments
 (0)