码迷,mamicode.com
首页 > 其他好文 > 详细

top k

时间:2016-11-03 09:41:52      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:dom   top   from   port   pre   turn   pivot   思路   random   

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

标签:dom   top   from   port   pre   turn   pivot   思路   random   

原文地址:http://www.cnblogs.com/bonelee/p/6025244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!