Skip to content

Commit 654512d

Browse files
committed
top k frequent elements
1 parent 6e65d41 commit 654512d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Runtime: 15ms
3+
* Time Complexity: O(n log n)
4+
* - ๋นˆ๋„ ๊ณ„์‚ฐ: O(n)
5+
* - ์ •๋ ฌ: O(u log u) โ‰ค O(n log n)
6+
* - k๊ฐœ ์ถ”์ถœ: O(k)
7+
*
8+
* Memory: 47.73MB
9+
* Space Complexity: O(n)
10+
* - HashMap: O(u) โ‰ค O(n)
11+
* - List: O(u) โ‰ค O(n)
12+
*
13+
* Approach: HashMap์œผ๋กœ ๋นˆ๋„ ๊ณ„์‚ฐ ํ›„ ์ •๋ ฌํ•˜์—ฌ top k ์ถ”์ถœ
14+
* - ๋ฐฐ์—ด ์ˆœํšŒํ•˜์—ฌ ๊ฐ ์›์†Œ์˜ ๋นˆ๋„ ๊ณ„์‚ฐ
15+
* - ๋นˆ๋„ ๊ธฐ์ค€ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
16+
* - ์ƒ์œ„ k๊ฐœ ์›์†Œ ์ถ”์ถœ
17+
*/
18+
class Solution {
19+
public int[] topKFrequent(int[] nums, int k) {
20+
Map<Integer, Integer> frequentMap = new HashMap<>();
21+
for (int num: nums) {
22+
frequentMap.put(num, frequentMap.getOrDefault(num, 0)+1);
23+
}
24+
25+
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(frequentMap.entrySet());
26+
list.sort((a, b) -> b.getValue() - a.getValue());
27+
28+
int[] result = new int[k];
29+
for (int i=0; i<k; i++) {
30+
result[i] = list.get(i).getKey();
31+
}
32+
33+
return result;
34+
}
35+
}

0 commit comments

Comments
ย (0)