[勇者闯LeetCode] 215. Kth Largest Element in an Array

来源:互联网 发布:自卫武器 知乎 编辑:程序博客网 时间:2024/05/17 15:20

[勇者闯LeetCode] 215. Kth Largest Element in an Array

Description

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.

Information

  • Tags: Heap | Divide and Conquer
  • Difficulty: Medium

Solution

使用QuickSelect,算法复杂度O(N).

from random import randintclass Solution(object):    def findKthLargest(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        obj = k - 1        l, r = 0, len(nums)-1        while l <= r:            pivot_idx = randint(l, r)            new_pivot_idx = self.partition(nums, l, r, pivot_idx)            if new_pivot_idx == obj:                return nums[new_pivot_idx]            elif new_pivot_idx > obj:                r = new_pivot_idx - 1            else:                l = new_pivot_idx + 1    def partition(self, nums, l, r, pivot_idx):        pivot_value = nums[pivot_idx]        new_pivot_idx = l        nums[pivot_idx], nums[r] = nums[r], nums[pivot_idx]        for i in range(l, r):            if nums[i] > pivot_value:                nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]                new_pivot_idx += 1        nums[r], nums[new_pivot_idx] = nums[new_pivot_idx], nums[r]        return new_pivot_idx
0 0
原创粉丝点击