当前位置: 首页 > news >正文

算法刷题之堆

1. heapq 堆

Python 中只有最小堆:

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

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

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

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

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

import heapqclass Solution:def findKthLargest(self, nums: List[int], k: int) -> int:# 最小堆变为最大堆a = list(map(lambda x: x * -1, nums))heapq.heapify(a)r = ""while k:r = heapq.heappop(a) * -1k -= 1return r 

题解二:

import heapqclass Solution:def findKthLargest(self, nums: List[int], k: int) -> int:nums.sort()return nums[-k]

3. 前 k 个高频单词

692. 前K个高频单词

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

题解一:最大堆 + 哈希表

import heapq
from collections import Counterclass Solution:def topKFrequent(self, words: List[str], k: int) -> List[str]:info = Counter(words)max_heap = []for word, cnt in info.items():heapq.heappush(max_heap, (-cnt, word))r = []while k:temp = heapq.heappop(max_heap)r.append(temp[1])k -= 1return r
  • Counter 会获取元素的个数,并按照从大到小排序

  • heapq.heappush([], item):可以添加元组,按照第一个元素进行排序,若第一个元素也相同,则按照字典序排序

def demo1():words = [(2, 'b'), (2, 'a'), (3, 'b'), (1, 'c')]min_heap = []for word in words:heapq.heappush(min_heap, word)while len(min_heap):print(heapq.heappop(min_heap))"""(1, 'c')(2, 'a')(2, 'b')(3, 'b')"""

题解二:cmp_to_key + sorted

import heapq
from functools import cmp_to_keyclass Solution:def topKFrequent(self, words: List[str], k: int) -> List[str]:# 哈希表保存 word 个数info = {}for word in words:info[word] = info.get(word, 0) + 1# 排序def compare(word1, word2):"""比较相邻两个单词"""if info[word1] == info[word2]:  # 单词数目相同,比较单词的字典序if word1 < word2:return -1else:return 1elif info[word1] > info[word2]: # 前一个单词的次数大于后一个单词次数,不交换return -1else:return 1    # 小于则交换return sorted(info.keys(), key=cmp_to_key(compare))[:k]

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

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

http://www.lryc.cn/news/44201.html

相关文章:

  • javaweb导师选择系统
  • LeetCode150 逆波兰表达式求值
  • 【Node.js】项目开发实战(中)
  • 记录一次 New Bing 英语陪练
  • 【Python】照片居然能变素描?不会画画但是咱会代码
  • 已解决正确配置git环境变量
  • 【逐步剖C】-第十章-自定义类型之结构体、枚举、联合
  • Windows Server 2016 中文版、英文版下载 (updated Mar 2023)
  • Linux 4G 通信实验
  • 华为OSPF技术详细介绍,保姆级,谁都能看懂(一)
  • 行人车辆检测与计数系统(Python+YOLOv5深度学习模型+清新界面)
  • SM3哈希算法的FPGA实现 I
  • 【数据结构与算法】线性表--数组
  • 剑指offer排序专题
  • 已解决Cannot open D:\Soft\Python36\Scripts\pip3-script.py
  • 3 步走,快速上手 API 接口测试
  • 爬虫-day1-正则表达式作业
  • 【半监督医学图像分割 2023 CVPR】RCPS
  • 【UVM实战练习项目】2、UVM验证环境基本框架搭建(实例一)(纯软件环境,方便日后测试使用)
  • 【web前端初级课程】第四章 什么是JavaScript
  • 数字中国建设进行时:吉林大学党委常务副书记冯正玉一行调研实在智能
  • 面试官灵魂拷问[二]:SQL 语句中 where 条件后写上 1=1 是什么意思?
  • 进程与线程的关系
  • 自定义异常
  • 基于springboot物资管理系统(程序+数据库)
  • 蓝桥杯Web组备赛笔记6
  • python控制语句
  • 华为OD机试题【最小叶子节点】用 Java 解 | 含解题说明
  • 【linux】多线程控制详述
  • SpringCloud学习-实用篇01