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.

Solution in python:

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def quickselect(arr, left, right):
            privot = arr[left]
            i = left
            j = right
            while i != j:
                while i < j and arr[j] >= privot:
                    j -= 1
                arr[i] = arr[j]
                while i < j and arr[i] <= privot:
                    i += 1
                # print("i:",i,"j:",j)
                arr[j] = arr[i]
            arr[i] = privot
            if i < len(arr) - k:
                return quickselect(arr, i+1, right)
            elif i > len(arr) - k:
                return quickselect(arr, left, i)
            else:
                return arr[i]
        return quickselect(nums, 0, len(nums)-1)

Complexity analysis:

  • Time complexity: E(O(N))
  • Space complexity: O(1)
最后修改日期: 2020年9月24日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。