法1:小根堆
Python
在Python的heapq模块中,当堆元素是数组(或列表)时,默认的比较规则是逐元素比较,直到找到第一个不同的元素。具体规则如下:
按元素顺序逐个比较:
比较数组的第一个元素,若不同则直接决定大小关系
若第一个元素相同,则比较第二个元素,依此类推
若所有元素都相同,则认为两个数组相等
# 写法1:
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
tmpMap = collections.Counter(nums)
minHeap = []
for key, val in tmpMap.items():
if len(minHeap) < k:
heapq.heappush(minHeap, [val, key])
else:
heapq.heappushpop(minHeap, [val, key])
return [item[1] for item in minHeap]
# 写法2:
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
tmp_map = collections.Counter(nums)
min_heap = []
for key, val in tmp_map.items():
if len(min_heap) < k:
heapq.heappush(min_heap, (val, key))
else:
heapq.heappushpop(min_heap, (val, key))
return [item[1] for item in min_heap]
Java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> valToCountMap = new HashMap<>();
for (int i : nums) {
valToCountMap.put(i, valToCountMap.getOrDefault(i, 0) + 1);
}
PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
for (Map.Entry<Integer, Integer> entry : valToCountMap.entrySet()) {
int val = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (count > queue.peek()[1]) {
queue.poll();
queue.offer(new int[]{val, count});
}
} else {
queue.offer(new int[]{val, count});
}
}
int[] res = new int[k];
for (int i = 0; i < k; ++i) {
res[i] = queue.poll()[0];
}
return res;
}
}