We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 380ee0c commit 2897867Copy full SHA for 2897867
top-k-frequent-elements/changchanghwang.go
@@ -0,0 +1,25 @@
1
+// Time: O(nlogn)
2
+// Space: O(n)
3
+func topKFrequent(nums []int, k int) []int {
4
+ hashMap := map[int]int{}
5
+ for _, num := range nums {
6
+ hashMap[num]++
7
+ }
8
+
9
+ result := [][]int{}
10
11
+ for key, value := range hashMap {
12
+ result = append(result, []int{key, value})
13
14
15
+ sort.Slice(result, func(i, j int) bool { // go의 sort는 quicksort를 기본적으로 사용한다. O(nlogn)
16
+ return result[i][1] > result[j][1]
17
+ })
18
19
+ resultNums := []int{}
20
+ for i := 0; i < k; i++ {
21
+ resultNums = append(resultNums, result[i][0])
22
23
24
+ return resultNums[:k]
25
+}
0 commit comments