Python heapq - one line solution


  • 2
    C
    class Solution:
    # @param {integer[]} nums
    # @param {integer} k
    # @return {integer}
    def findKthLargest(self, nums, k):
        return heapq.nlargest(k, nums)[-1]
    

    Seems not the fastest one... Any better solution?

    Thanks!


  • 0
    H

    This is 12ms faster

    import heapq
    class Solution:
        # @param {integer[]} nums
        # @param {integer} k
        # @return {integer}
        def findKthLargest(self, nums, k):
            heap=[]
            for i in nums:
                heapq.heappush(heap,-i)
            for i in range(k):
                res=-heapq.heappop(heap)
            return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.