题解 | #寻找第K大#

寻找第K大

http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

-- coding:utf-8 --

class Solution: def findKth(self, a, n, K): # write code here if not a or n<1 or K>n: return -1 start,end = 0,n-1 K = n - K while True: q = self.partition(a,start,end)

print(q)

        if q == K:
            return a[q]
        if q < K:
            start = q + 1
        else:
            end = q - 1
    return -1

def partition(self,a,start,end):
    if start==end:
        return start
    x = a[end]
    i = start - 1
    for j in range(start,end):
        if a[j] < x:
            i += 1
            a[i],a[j] = a[j],a[i]
    i += 1
    a[i],a[end] = a[end],a[i]
    return i
    
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务