算法刷题之堆

爱被打了一巴掌 2023-09-30 21:27 45阅读 0赞

1. heapq 堆

Python 中只有最小堆:

  1. import heapq
  2. a = []
  3. heapq.heappush(a, 3) # 添加元素
  4. heapq.heappush(a, 2)
  5. heapq.heappush(a, 1)
  6. while len(a): # 判断堆的长度
  7. print(heapq.heappop(a)) # 弹出堆顶元素
  8. # 将列表转换为最小堆
  9. nums = [2, 3, 1, 4, 5, 6]
  10. heapq.heapify(nums)
  11. while len(nums):
  12. print(heapq.heappop(nums))
  13. # 转换为最大堆
  14. nums_1 = [2, 3, 1, 4, 5, 6]
  15. max_heap = []
  16. for i in max_heap:
  17. heapq.heappush(max_heap, i * -1) # 对当前元素乘 -1 ,取出来后再乘以 -1

2. 数组中的第 K 个最大元素

215. 数组中的第K个最大元素

  1. 给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
  2. 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
  3. 示例 1:
  4. 输入: [3,2,1,5,6,4] k = 2
  5. 输出: 5
  6. 示例 2:
  7. 输入: [3,2,3,1,2,4,5,5,6] k = 4
  8. 输出: 4
  9. 提示:
  10. 1 <= k <= nums.length <= 104
  11. -104 <= nums[i] <= 104

题解一:最小堆变成最大堆

  1. import heapq
  2. class Solution:
  3. def findKthLargest(self, nums: List[int], k: int) -> int:
  4. # 最小堆变为最大堆
  5. a = list(map(lambda x: x * -1, nums))
  6. heapq.heapify(a)
  7. r = ""
  8. while k:
  9. r = heapq.heappop(a) * -1
  10. k -= 1
  11. return r

题解二:

  1. import heapq
  2. class Solution:
  3. def findKthLargest(self, nums: List[int], k: int) -> int:
  4. nums.sort()
  5. return nums[-k]

3. 前 k 个高频单词

692. 前K个高频单词

  1. 给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。
  2. 返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。
  3. 示例 1
  4. 输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
  5. 输出: ["i", "love"]
  6. 解析: "i" "love" 为出现次数最多的两个单词,均为2次。
  7. 注意,按字母顺序 "i" "love" 之前。
  8. 示例 2
  9. 输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
  10. 输出: ["the", "is", "sunny", "day"]
  11. 解析: "the", "is", "sunny" "day" 是出现次数最多的四个单词,
  12. 出现次数依次为 4, 3, 2 1 次。
  13. 注意:
  14. 1 <= words.length <= 500
  15. 1 <= words[i] <= 10
  16. words[i] 由小写英文字母组成。
  17. k 的取值范围是 [1, 不同 words[i] 的数量]

题解一:最大堆 + 哈希表

  1. import heapq
  2. from collections import Counter
  3. class Solution:
  4. def topKFrequent(self, words: List[str], k: int) -> List[str]:
  5. info = Counter(words)
  6. max_heap = []
  7. for word, cnt in info.items():
  8. heapq.heappush(max_heap, (-cnt, word))
  9. r = []
  10. while k:
  11. temp = heapq.heappop(max_heap)
  12. r.append(temp[1])
  13. k -= 1
  14. return r
  • Counter 会获取元素的个数,并按照从大到小排序
  • heapq.heappush([], item):可以添加元组,按照第一个元素进行排序,若第一个元素也相同,则按照字典序排序

    def demo1():

    1. words = [(2, 'b'), (2, 'a'), (3, 'b'), (1, 'c')]
    2. min_heap = []
    3. for word in words:
    4. heapq.heappush(min_heap, word)
    5. while len(min_heap):
    6. print(heapq.heappop(min_heap))
    7. """
    8. (1, 'c')
    9. (2, 'a')
    10. (2, 'b')
    11. (3, 'b')
    12. """

题解二:cmp_to_key + sorted

  1. import heapq
  2. from functools import cmp_to_key
  3. class Solution:
  4. def topKFrequent(self, words: List[str], k: int) -> List[str]:
  5. # 哈希表保存 word 个数
  6. info = {
  7. }
  8. for word in words:
  9. info[word] = info.get(word, 0) + 1
  10. # 排序
  11. def compare(word1, word2):
  12. """比较相邻两个单词"""
  13. if info[word1] == info[word2]:
  14. # 单词数目相同,比较单词的字典序
  15. if word1 < word2:
  16. return -1
  17. else:
  18. return 1
  19. elif info[word1] > info[word2]: # 前一个单词的次数大于后一个单词次数,不交换
  20. return -1
  21. else:
  22. return 1 # 小于则交换
  23. return sorted(info.keys(), key=cmp_to_key(compare))[:k]

注意:sortedkey 参数提供的比较函数,默认只能提供一个元素,如果想两两比较,提供两个元素可以使用 cmp_to_key 方法。

参考:692.前K个高频单词 Python双解,包教包会!

发表评论

表情:
评论列表 (有 0 条评论,45人围观)

还没有评论,来说两句吧...

相关阅读

    相关 贪心算法

    1.递增数组 题目链接:[递增数组][Link 1] 题目介绍: > 牛牛有一个数组array,牛牛可以每次选择一个连续的区间,让区间的数都加1,他想知道把这

    相关 算法-

    剑指Offer快速过了一遍 字节-飞书高频题-前15 各公司的高频面试算法题,可在 [CodeTop][]查询 (1) 146. LRU 缓存机制 我的实现