Title description
Enter n integers and find the smallest K number. For example, if you enter the 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4,.
Idea: To maintain a maximum heap with a size of k, first initialize the first k numbers, and then slide the window. If it is larger than the top of the heap, discard it directly, exchange if it is smaller than the top of the heap, and then adjust the heap.
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
heap = self.Build_Heap(tinput[:k])
for i in range(k, len(tinput)):
if tinput[i] >= heap[0]:
continue
else:
heap[0] = tinput[i]
for i in range(k-1,-1,-1):
self.Adjust_Heap(heap, 0, k)
print heap
return heap
def Adjust_Heap(self, tinput, root, heap_size):
left = 2*root+1
right = left + 1
larger = root
if left < heap_size and tinput[left] > tinput[root]:
larger = left
if right < heap_size and tinput[right] > tinput[root]:
larger = right
if larger != root:
tinput[root], tinput[larger] = tinput[larger], tinput[root]
self.Adjust_Heap(tinput, larger, heap_size)
def Build_Heap(self, heap):
HeapSize = len(heap)
for i in range((HeapSize-1)//2, -1, -1):
self.Adjust_Heap(heap,i, HeapSize)
return heap
s = [4,5,1,6,2,7,3,8,435,32,13,5,2,99,0,-67,-7,56,35,637,73,2]
m = Solution()
m.GetLeastNumbers_Solution(s, 8)