215. Kth Largest Element in an Array

  1. leetcode record

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.

Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

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

解题思路:
从大到小,快速排序,返回第 k-1 个数

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        l, h = 0,len(nums)-1
        self.quicksort(nums,l,h)
        return nums[k - 1]

    def quicksort(self,nums,l,h):
        if l < h:
            pivotpos = self.partition(nums,l,h)
            self.quicksort(nums,l,pivotpos - 1)
            self.quicksort(nums,pivotpos + 1,h)

    def partition(self,nums,l,h):
        p = nums[l]
        while l < h:
            while l < h and nums[h] <= p:
                h -= 1
            nums[l] = nums[h]
            while l < h and nums[l] >= p:
                l += 1
            nums[h] = nums[l]
        nums[l] = p
        return l

leetcode record


请多多指教。

文章标题:215. Kth Largest Element in an Array

本文作者:顺强

发布时间:2020-04-10, 01:20:12

原始链接:http://shunqiang.ml/leetcode-215-kth-largest/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏