Python 3 Ways to solve this problem


  • 0

    System sorted function

    return sorted(nums)[-k]
    

    & Min-Heap

    q = []
            for c in nums:
                heapq.heappush(q, -c)
            for i in xrange(k - 1):
                heapq.heappop(q)
            return -heapq.heappop(q)
    

    & Quicksort

            def partition(left, right):
                strt, end = left + 1, right
                while strt <= end:
                    if nums[strt] < nums[left] and nums[end] > nums[left]:
                        nums[strt], nums[end] = nums[end], nums[strt]
                        strt += 1
                        end -= 1
                    if nums[strt] >= nums[left]:
                        strt += 1
                    if nums[end] <= nums[left]:
                        end -= 1
                nums[left], nums[end] = nums[end], nums[left]
                return end
            left, right = 0, len(nums) - 1
            while True:
                pos = partition(left, right)
                if pos == k - 1:
                    return nums[pos]
                elif pos > k - 1:
                    right = pos - 1
                else:
                    left = pos + 1
    

Log in to reply
 

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