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

  • 相关阅读:
    四种读写方案IO流 (JAVA)
    如何保证ArrayList线程安全
    异常总结 (经典)
    JAVA反射机制
    移位运算符(JAVA)
    return和finally的执行顺序
    适配器模式(接口)
    2020年大厂Java面试题集锦,干货集锦,快来集合了!
    资深架构师解析springcloud分布式微服务的实现
    HTTP最全最新资料大全
  • 原文地址:https://www.cnblogs.com/plank/p/9156805.html
Copyright © 2020-2023  润新知