class Solution(object):
def smallestK(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
if k<=0:return []
self.data=arr[:k]
self.create_max_heap()
for i in arr[k:]:
if i<self.data[0]:
self.data[0]=i
self.sift(0,k-1)
return self.data
def sift(self,low_index,high_index):
temp=self.data[low_index]
i=low_index
j=2*i+1
while j<=high_index:
if j+1<=high_index and self.data[j]<self.data[j+1]:j+=1
if self.data[j]>temp:
self.data[i]=self.data[j]
i=j
j=2*i+1
else:break
self.data[i]=temp
def create_max_heap(self):
for i in range((len(self.data)-1-1)//2,-1,-1):
self.sift(i,len(self.data)-1)