zoukankan      html  css  js  c++  java
  • 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)。

  • 相关阅读:
    docker 清理日志文件
    POJ2182 Lost Cows
    POJ3468
    楼兰图腾
    P2024 [NOI2001]食物链
    POJ1733 Parity game
    洛谷P1196 [NOI2002]银河英雄传说
    洛谷P1955 [NOI2015]程序自动分析
    CF 660 C. Uncle Bogdan and Country Happiness
    CF 660A&B
  • 原文地址:https://www.cnblogs.com/plank/p/9156805.html
Copyright © 2011-2022 走看看