最小的k个数
Medium; heap; array; sorting;
Last updated
Medium; heap; array; sorting;
Last updated
[4,5,1,6,2,7,3,8],4 [1,2,3,4]import heapq
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
#
#method 1: sort and then return top k . O(nlogn) for sorting
#method 2: heap sort using max heap to pop n-k elements return the last k elements
# 1. heapify the first K element
# 2. loop throught the remaining n-k element and pop the
# 3. return the last k element
#base case
if not tinput or (k > len(tinput) or k<1):
return []
heap = [0]*k
# O(k)
for i in range(k):
heap[i] = -tinput[i]
heapq.heapify(heap)
# TIme: O((n-k)logk)
for i in range(k, len(tinput)):
if -tinput[i] > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, -tinput[i])
# reverse list
# klognk
res = [0]*k
for i in range(k-1, -1, -1):
res[i] = -heapq.heappop(heap)
return res