LeetCode-215. Kth Largest Element in an Array

https://leetcode.com/problems/kth-largest-element-in-an-array/

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

Solution

# 快排
class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        #return sorted(nums)[-k]
        left = 0
        right = len(nums) - 1
        while True:
            temp = self.partition(nums,left,right)
            # print temp
            if temp == k -1:
                return nums[temp]
            if temp > k-1:
                right = temp - 1
            else:
                left = temp + 1
        
        
    def partition(self,nums,left,right):
        pivot = nums[left]
        l = left + 1
        r = right
        while l <= r:
            if nums[l] < pivot and nums[r] > pivot:
                nums[l], nums[r] = nums[r], nums[l]
                l += 1
                r -= 1
            if nums[l] >= pivot:
                l += 1
            if nums[r] <= pivot:
                r -= 1
        nums[left], nums[r] = nums[r], nums[left]
        return r
# 堆排

posted @ 2016-12-09 15:24  BinWone  阅读(160)  评论(0编辑  收藏  举报