diff --git a/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements.go b/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements.go new file mode 100644 index 0000000..39be19b --- /dev/null +++ b/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements.go @@ -0,0 +1,29 @@ +package leetcode + +func TopKFrequentElements(nums []int, k int) []int { + bucket := make([][]int, len(nums)) + freqTable := map[int]int{} + for _, num := range nums { + freqTable[num]++ + } + for num, freq := range freqTable { + freq-- + if bucket[freq] == nil { + bucket[freq] = make([]int, 0) + } + bucket[freq] = append(bucket[freq], num) + } + result := []int{} + count := 0 + for i := len(bucket) - 1; i >= 0; i-- { + if bucket[i] == nil { + continue + } + result = append(result, bucket[i]...) + count += len(bucket[i]) + if count == k { + break + } + } + return result +} diff --git a/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements_test.go b/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements_test.go new file mode 100644 index 0000000..b348bae --- /dev/null +++ b/leetcode/0347.Top-K-Frequent-Elements/347. Top K Frequent Elements_test.go @@ -0,0 +1,48 @@ +package leetcode + +import ( + "reflect" + "sort" + "testing" +) + +// 填入 function input type +type parameters0347 struct { + nums []int + k int +} + +func TestTopKFrequentElements(t *testing.T) { + tests := []struct { + parameters0347 + // 填入 function output type + ans []int + }{ + // 填入 test case + { + parameters0347{[]int{1, 1, 1, 2, 2, 3}, 2}, + []int{1, 2}, + }, + { + parameters0347{[]int{1}, 1}, + []int{1}, + }, + { + parameters0347{[]int{6, 6, 6, 0, 6, 6, 6}, 1}, + []int{6}, + }, + } + + for _, test := range tests { + t.Run("Test TopKFrequentElements", func(t *testing.T) { + // 完整輸入參數 + result := TopKFrequentElements(test.parameters0347.nums, test.parameters0347.k) + // compare 的方式需視情況調整 + sort.Ints(result) + sort.Ints(test.ans) + if !reflect.DeepEqual(result, test.ans) { + t.Errorf("TopKFrequentElements(%+v) got %+v, want %+v", test.parameters0347, result, test.ans) + } + }) + } +} diff --git a/leetcode/0347.Top-K-Frequent-Elements/README.md b/leetcode/0347.Top-K-Frequent-Elements/README.md new file mode 100644 index 0000000..86a7bbb --- /dev/null +++ b/leetcode/0347.Top-K-Frequent-Elements/README.md @@ -0,0 +1,23 @@ +# 347. Top K Frequent Elements + + + +給定整數陣列 `nums` 和整數 `k` +回傳 `nums` 中前 `k` 個高頻率出現的數字 +回傳的數字可以用任何順序出現 +答案已保證是獨一無二的,且要求時間複雜度必須優於 $O(n \cdot log(n))$ + +假設 `nums` 長度是 `n` +則出現頻率最高的次數也就是 `n`,意思是「頻率」數值的範圍有限 +因此,可以建立一個長度為 `n` 的 bucket,將相應出現頻率的數字放到指定的 index + +一開始先用 $O(n)$ 掃 `nums` 將所有數字及其頻率記錄在 hash table +接著掃一次這個 hash table,將出現頻率記錄在相應 bucket +最後從 bucket 的最後取出前 `k` 個 element + +這樣子的時間和空間複雜度都只需要 $O(n)$ + +## Takeaway + +- Hash Table +- Counting Sort