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/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值