7.10.2 (python)堆的应用及Leetcode题目解析

我们简单看几道二叉堆/优先队列的应用。

215. Kth Largest Element in an Array

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.

题目解析:

求一个数组前k个最大数,或者只要第k个最大数,是很常见的问题,有多种思路和写法,但是在python 面前,只需一行。

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        import heapq 
        return heapq.nlargest(k, nums)[-1]
        

239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] Explanation:
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

题目解析:

相当于在k个数里找最大的,但是这K个数是渐变的。最直接的方法是,遍历数组O(n),每一次观察,拿出这k个数,找最大的O(k),每次滑动都要遍历窗口中的数,明显效率略低。我们进行了改进,我们注意滑动窗口移动时,左边滑出去的值和右边滑进来的值,当上一次的最大值cur_max没有滑出去,那么只需要滑进来的值与它比较即可;否则,重新搜索新的最大值。有一定的堆的思想,但是甚至不见它的踪影。

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        import heapq        
        res = []
        if not nums:
            return res
        cur_max = nums[0]
        
        for num in nums[:k]:
            cur_max = max(cur_max, num)        
        res.append(cur_max)
        
        ix = 0
        for num in nums[k:]:
            if nums[ix] != cur_max:
                cur_max = max(cur_max, num)
            else:
                cur_max = nums[ix+1]
                for n in nums[ix+2: ix+1+k]:
                    cur_max = max(cur_max, n)
                # cur_max = heapq.nlargest(1, nums[ix+1: ix+1+k])[0] # 也可用这一行
            res.append(cur_max)
            ix += 1
        return res
            

451. Sort Characters By Frequency

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

题目解析:

放到这部分,甚至显得不合适,因为python中的工具太强大了。Counter完美解决统计频率相关的问题。不再废话。

class Solution:
    def frequencySort(self, s: str) -> str:
        if not s:
            return ""
        from collections import Counter        
        c = Counter(s)
        
        res = ""
        for item in c.most_common():
            res += item[0]*item[1]
        return res

703. Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

题目解析:

经典的第k个最大(小)的问题,该提要求实现这样的一个对象。笨方法是,每次add时我们对数据进行排序,这太蠢了。常规方法是,初始化时排序,每次add时,我们将val插入到合适的位置,O(logn)的操作。这里,我们充分利用堆的性质,python 中heapq实现了最小堆,这样我们建一个大小为k的堆,初始化及add操作后,始终保持这个大小,让堆顶元素为第k个最大的值。很省事的就是,当add的值小于堆顶时,不必插入直接返回结果,这是这个设计结构的优势。

class KthLargest:
    import heapq
    def __init__(self, k: int, nums: List[int]):
        self.data = []
        for num in nums:
            if len(self.data) < k:
                heapq.heappush(self.data, num)                
            else:
                self.kth = self.data[0]
                if num > self.kth:
                    heapq.heappushpop(self.data, num)
        self.k = k

    def add(self, val: int) -> int:
        if len(self.data) >= self.k and val < self.data[0]:
            return self.data[0]
        heapq.heappush(self.data, val)
        if len(self.data) > self.k:
            heapq.heappop(self.data)
        return self.data[0]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值