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)。

  • 相关阅读:
    jquery+NHibernate3.3.3+MVC的分页效果
    An exception occurred during configuration of persistence layer.
    StringHelpers
    发送带有认证信息的HTTP请求并取回响应
    script的defer和async
    location.origin兼容
    写法导致的兼容性问题
    正则表达式应用收集
    列表数字对齐布局
    轮盘赌算法
  • 原文地址:https://www.cnblogs.com/plank/p/9156805.html
Copyright © 2011-2022 走看看