Given an integer array nums
and an integer k
, return thek
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
k
is in the range [1, the number of unique elements in the array]
.Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
題目給了一個整數陣列 nums 還有一個正整數 k
要求寫一個演算法來找出前 k 個最常出現的整數
直覺的作法是用一個 HashMap 來紀錄每個元素出現的次數
然後對這個 HashMap 的 key 做 sort 但這樣做會是 O(nlogn)
要比 O(nlogn) 還要優化