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

  • 相关阅读:
    webapi 导入CSV文件
    webapi 导出CSV文件
    .net 压缩文件夹和解压
    SSH免密码登陆以及穿越跳板机
    hbase shell删除键不听使唤
    百度分享插件wbuid属性无法@指定微博
    iOS safari BUG 总结
    论zeroclipboard的各种爽翻天用法
    Android Studio 使用技巧
    安装第三方包web.py发生的错误
  • 原文地址:https://www.cnblogs.com/plank/p/9156805.html
Copyright © 2011-2022 走看看