首页 > 代码库 > top k
top k
def top_k(arr, left, right, k): if left >= right: return pivot = arr[right] index = left for i in range(left, right): if arr[i] < pivot: arr[i], arr[index] = arr[index], arr[i] index += 1 arr[index], arr[right] = arr[right], arr[index] num = index-left+1 if num == k: return elif num < k: top_k(arr, index+1, right, k-num) else: top_k(arr, left, index-1, k) from random import randint a=[] for i in range(30): a.append(randint(0, 20)) print a top_k(a, 0, len(a)-1, 5) print a print a[:5]
采用快排思路来做,上面的输出:
[9, 2, 10, 10, 12, 20, 18, 7, 15, 12, 17, 1, 16, 6, 17, 0, 16, 10, 18, 4, 1, 10, 14, 15, 4, 9, 11, 7, 3, 20] [2, 1, 0, 1, 3, 18, 7, 15, 12, 17, 9, 16, 6, 17, 10, 16, 10, 18, 4, 10, 10, 14, 15, 4, 9, 11, 7, 12, 20, 20] [2, 1, 0, 1, 3]
注意:k个元素未必是有序的!
top k
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。