LeetCode215. 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.

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

思路:

利用快速排序里边partition()函数,在待搜索列表中不断二分搜索,可以得到元素位置。

代码如下:

import random
class Solution(object):
    def findKthLargest(self, nums, k):
        if not nums:
            return
        random.shuffle(nums)  #important
        index = self.find_helper(nums, 0, len(nums) - 1, k - 1)
        return nums[index]

    def find_helper(self, nums, left, right, k):
        big_index = left
        for i in range(left, right):
            if nums[i] > nums[right]:
                if i > big_index:
                    nums[i], nums[big_index] = nums[big_index], nums[i]
                big_index += 1
        nums[big_index], nums[right] = nums[right], nums[big_index]
        if big_index < k:
            big_index = self.find_helper(nums, big_index + 1, right, k)
        elif big_index > k:
            big_index = self.find_helper(nums, left, big_index - 1, k)
        return big_index

在随机打乱的输入列表里边,这种方法的时间复杂度为O(n)。注意‘random.shuffle(nums)’这行语句,这随机打乱了列表。如果不这样,这种算法在比较坏的情况下的时间复杂度为O(n*n)。

猜你喜欢

转载自www.cnblogs.com/plank/p/9156805.html