leetcode 215. Kth Largest Element in an Array(python)

描述

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

Note:

You may assume k is always valid, 1 ≤ k ≤ array's length.

解析

根据题意,只需要把列表 nums 排序,找出 Kth 的值即可,解答简单,也可用堆数据结构进行排序解答。

解答

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        nums.sort()
        return nums[-k]

运行结果

Runtime: 44 ms, faster than 90.84% of Python online submissions for Kth Largest Element in an Array.
Memory Usage: 14.2 MB, less than 62.15% of Python online submissions for Kth Largest Element in an Array.

解答

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        heapify(nums)
        while len(nums) > k:
            heappop(nums)
        return nums[0]

运行结果

Runtime: 80 ms, faster than 29.76% of Python online submissions for Kth Largest Element in an Array.
Memory Usage: 14.1 MB, less than 82.14% of Python online submissions for Kth Largest Element in an Array.        

原题链接:https://leetcode.com/problems/kth-largest-element-in-an-array/

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/114100446