寻找最大的K个数

编程之美(2-5)

解法2:

import random
def partion(L):
    div = L[random.choice(range(len(L)))]
    L0 = []
    L1 = []
    for value in L:
        if value >= div:
            L1.append(value)
        else:
            L0.append(value)

    return (L0,L1)

def KBig(k,L):
    if len(L) <= k:
        return L

    (L0,L1) = partion(L)
    if len(L1) == k:
        return L1
    elif len(L1) > k:
        return KBig(k,L1)
    else:
        return L1+KBig(k-len(L1),L0)

 解法四:堆解法

#构建初始堆
def constructHeap(L,pos):
    if 0 == pos//2:
        return
    parentPos = pos//2
    if L[pos-1] >= L[parentPos-1]:
        return
    else:
        L[pos-1],L[parentPos-1] = L[parentPos-1],L[pos-1]
        constructHeap(L,parentPos)
#替换最小堆中根元素后保持最小堆属性
def remainHeap(L,pos):
    LchildPos, RchildPos = pos * 2,pos * 2 + 1

    if LchildPos > len(L):
        return

    if RchildPos > len(L):
        tempPos = LchildPos
    else:
        tempPos = LchildPos if(L[LchildPos-1] < L[RchildPos-1]) else RchildPos

    if L[pos-1] <= L[tempPos-1]:
        return
    else:
        L[pos-1],L[tempPos-1] = L[tempPos-1],L[pos-1]
        remainHeap(L,tempPos)
        
SRC =[97,98,100,1,84,56,705,1,5,3,6,234]
k=4
L = []
for i in SRC[:k]:
    L.append(i)
    constructHeap(L,len(L))
    print(L)

for i in SRC[k:]:
    if i > L[0]:
        L[0] = i
        remainHeap(L,1)
print(L)

 

posted @ 2014-01-08 22:13  平凡之路  阅读(204)  评论(0)    收藏  举报