面试题 17.14. 最小K个数
设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
示例:
输入: arr = [1,3,5,7,2,4,6,8], k = 4
输出: [1,2,3,4]
提示:
0 <= len(arr) <= 100000
0 <= k <= min(100000, len(arr))
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-k-lcci
import heapq class Solution: def smallestK(self, arr: List[int], k: int) -> List[int]: if k>len(arr) or k==0: return [] heap = [] for i in arr[:k]: heapq.heappush(heap,-i) for i in arr[k:]: if i<-heap[0]: heapq.heappop(heap) heapq.heappush(heap,-i) res = [] for i in range(k): res.append(-heapq.heappop(heap)) return res[::-1]