堆排序取Top_k
作者:互联网
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)
求最小的topk则构建最大堆(该最大值逐渐被弱化,变成最小的第topk个值),最大的topk同理
标签:arr,int,List,Top,堆排序,topk,data,self 来源: https://blog.csdn.net/qq_45692660/article/details/118366434