python针对大数组获取第k大元素方法

假设第k大元素数值为Kmax
partition后大于Kmax的数在数组右面,小于Kmax数在数组左面,Kmax刚好在第k位。我理解实现思路跟用快排找到第k大元素类似,没有具体研究

import numpy as np
arr = list() 
# (填充操作省略)
arr = np.array(arr)
max_k = np.partition(arr, -k)[-k])

如果k比较小,还有个堆排序的方式
https://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p04_find_largest_or_smallest_n_items.html

猜你喜欢

转载自blog.csdn.net/weixin_42219542/article/details/108350969