取出列表中第N大的数
array=list(range(10)) random.shuffle(array) print(array) def func1(array,n): d,k={},n while k>0: maxnum,maxindex=-float("inf"),0 for index,value in enumerate(array): if index not in d: if value>=maxnum: maxnum=value maxindex=index d[maxindex]=maxnum k-=1 return list(d.values())[2]#因为python现在的版本字典默认是有序的,所以可以这么用
方案2,建立一个小根堆,保存前三大的数据,时间复杂度nlogk
def list2bucket(li,i): buckets=[[] for _ in range(10)] for val in li: digit=val//(10**i)%10 buckets[digit].append(val) return buckets def bucket2lit(buckets): li=[] for bucket in buckets: for val in bucket: li.append(val) return li def radix_sort(li): max_val=max(li) i=0 while 10**i<=max_val: li=bucket2lit(list2bucket(li,i)) i+=1 return li print(radix_sort(array)[-3])