美文网首页
leetcode-215-数组中第K大的元素-堆

leetcode-215-数组中第K大的元素-堆

作者: 葫芦葫芦快显灵 | 来源:发表于2019-07-17 19:58 被阅读0次

    题目:
    在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

    示例 1:

    输入: [3,2,1,5,6,4] 和 k = 2
    输出: 5

    示例2:

    输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
    输出: 4
    说明:

    你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度

    思路:

    1. 直接排序,取第k大的元素即可, 时间复杂度 O(nlogn)(快排的情况)
    2. 使用优先队列,维护一个K大的小顶堆 时间复杂度 O(logn)

    code:

    #ruby  ..没找到ruby里面的优先队列。。。
    def find_kth_largest(nums, k)
        temp_arr = nums.sort
        temp_arr[-k]
    end
    
    #python3
    class Solution:
        def findKthLargest(self, nums: List[int], k: int) -> int:
            heap = []
            for num in nums[:k]:
                heapq.heappush(heap, num)
            for num in nums[k:]:
                if num > heap[0]:
                    heapq.heappop(heap)
                    heapq.heappush(heap, num)
            return heap[0]
    

    相关文章

      网友评论

          本文标题:leetcode-215-数组中第K大的元素-堆

          本文链接:https://www.haomeiwen.com/subject/ejnclctx.html