Medium
,Array
,Hash Table
,Heap
,Divide and Conquer
,Sorting
Given an integer array nums
and an integer k
, return the k
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:
nums.length
<= 105nums[i]
<= 104k
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.
function topKfrequent(nums, k) {
const map = new Map();
for (const num of nums) {
map.set(num, map.get(num) + 1 || 1);
}
// sort
const sorted = [...map.entries()].sort((a, b) => b[1] - a[1]);
const result = [];
for (let i = 0; i < k; i++) {
result.push(sorted[i][0]);
}
return result;
}
MarsgoatMay 22, 2023
function topKFrequent(nums: number[], k: number): number[] {
const map = new Map<number, number>();
nums.forEach((num) => map.set(num, (map.get(num) || 0) + 1));
const sortedArr = [...map.entries()].sort((a, b) => b[1] - a[1]);
// 這樣慢一點 但是可以一行
return sortedArr.slice(0, k).map((num) => num[0]);
}
SheepMay 22, 2023
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if len(nums) == k: return nums
counter = Counter(nums)
# Max heap
heap = [(-freq, num) for num, freq in counter.items()]
heapq.heapify(heap)
ans = []
for _ in range(k):
ans.append(heapq.heappop(heap)[1])
return ans
看了題解發現可以縮
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums): return nums
counter = Counter(nums)
return heapq.nlargest(k, counter.keys(), key=counter.get)
TC:
SC:
Ron ChenMon, May 22, 2023
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return [n for n, _ in Counter(nums).most_common(k)]
Yen-Chi ChenMon, May 22, 2023