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

算法题-哈希表01

什么是哈希表

当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法了。

哈希函数

哈希冲突

01-有效字母异位词

链接:242. 有效的字母异位词 - 力扣(LeetCode)

  1. 题目描述:

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1: 输入: s = "anagram", t = "nagaram" 输出: true

示例 2: 输入: s = "rat", t = "car" 输出: false

说明: 你可以假设字符串只包含小写字母。

  1. 思路:

用一个hash表存储,索引表示值,值表示出现的次数,s加一,t减一,然后遍历hash表,如果出现不等于0的数字,则返回False,表名不是异位词。遍历完都是0,就是异位词,返回false

  1. 代码
class Solution(object):def isAnagram(self, s, t):""":type s: str:type t: str:rtype: bool"""records = [0] * 26for char in s:records[ord(char) - ord('a')] += 1for char in t:records[ord(char) - ord('a')] -= 1for record in records:if record != 0:return Falsereturn True

02-两个数组的交集

链接:349. 两个数组的交集 - 力扣(LeetCode)

  1. 题目描述

题意:给定两个数组,编写一个函数来计算它们的交集。

  1. 思路:

哈希表法:

一个hash表,索引表示数字值,值表示是否出现过

  • 遍历第一个数组,更新,True表示出现过
  • 遍历第二个数组,如果发现对应的是True,则表示是交集,加入到结果集result中,并把这个hash值置为False
  1. 代码:
class Solution(object):def intersection(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""records = [False] * 1001result = []for num in nums1:records[num] = Truefor num in nums2:if records[num]:result.append(num)# 这里很关键,置为False后表示,不会再加入这个元素了records[num] = Falsereturn result
  1. 其他方法
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:# 使用哈希表存储一个数组中的所有元素table = {}for num in nums1:table[num] = table.get(num, 0) + 1# 使用集合存储结果res = set()for num in nums2:if num in table:res.add(num)del table[num]return list(res)
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:count1 = [0]*1001count2 = [0]*1001result = []for i in range(len(nums1)):count1[nums1[i]]+=1for j in range(len(nums2)):count2[nums2[j]]+=1for k in range(1001):if count1[k]*count2[k]>0:result.append(k)return result
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:return list(set(nums1) & set(nums2))

03-快乐数

链接:202. 快乐数 - 力扣(LeetCode)

  1. 描述

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

  1. 思路:

这里数字的平方和需要判断是否出现过,要判断一个数是否反复出现的时候,就要想到hash了,set和数组都行,这里用set来存储和。

数字拆解方法有两种

  • divmod函数拆解出商和余数
  • 转化成字符串,取出单个字符后转化成数字
  1. 代码
class Solution(object):def isHappy(self, n):""":type n: int:rtype: bool"""record = set()while n not in record:new_sum = 0for i in str(n):new_sum += int(i) ** 2if new_sum == 1:return Truerecord.add(n)n = new_sumreturn False
class Solution(object):def isHappy(self, n):""":type n: int:rtype: bool"""seen = set()while n not in seen:# 在计算之前加seen.add(n)n = sum(int(i) ** 2 for i in str(n))if n == 1:return True# 加入元素不能写在这里,一加入那肯定判断在seen中了呀# seen.add(n)return False


文章转载自:

http://XFp2ZXfD.yysqz.cn
http://j0f7lG1A.yysqz.cn
http://Ykv40U5K.yysqz.cn
http://WCJ7iFcR.yysqz.cn
http://kKh9FWvP.yysqz.cn
http://ZYQYSPhT.yysqz.cn
http://ZVjcFg29.yysqz.cn
http://SBEklOzU.yysqz.cn
http://JPKRI3g2.yysqz.cn
http://0K2pXjTK.yysqz.cn
http://UjEptWXZ.yysqz.cn
http://zmugr3Fj.yysqz.cn
http://7bDoPsfd.yysqz.cn
http://IgBDgx8a.yysqz.cn
http://9zXqWbDH.yysqz.cn
http://7qugmJsK.yysqz.cn
http://HTLpkWsr.yysqz.cn
http://avw4tzNz.yysqz.cn
http://ZbHasYXk.yysqz.cn
http://6mUMA7iR.yysqz.cn
http://umzmlQzB.yysqz.cn
http://Gexn77Tb.yysqz.cn
http://l18kodHp.yysqz.cn
http://t6QoKxOx.yysqz.cn
http://t7F6gB8m.yysqz.cn
http://Vtn3uwyx.yysqz.cn
http://HaEDwiFr.yysqz.cn
http://6saMzSn7.yysqz.cn
http://YggsaXOx.yysqz.cn
http://heUB5gez.yysqz.cn
http://www.dtcms.com/a/371751.html

相关文章:

  • 云平台面试内容(二)
  • Carlsson_HEAL-SWIN_A_Vision_Transformer_On_The_Sphere_CVPR_2024_paper_analysis
  • 微服务的保护方式以及Sentinel详解
  • 【jenkins】--安装部署
  • Vue 路由传参的四种方式
  • HTML 表格基础
  • CD76.【C++ Dev】AVL的模拟实现(1) 以左单旋为切口,分析旋转规律
  • 中国计算机发展史
  • LeetCode刷题记录----20.有效的括号(Easy)
  • 从voice和练习发声谈起
  • 5.python——数字
  • 数据化运营的工作流程
  • llama_factory 安装以及大模型微调
  • Linux | i.MX6ULL 搭建 Web 服务器(第二十章)
  • 量子電腦組裝之三
  • 适配器详细
  • GD32自学笔记:5.定时器中断
  • 前端三件套简单学习:HTML篇1
  • Android --- SystemUI 导入Android Studio及debug
  • 服务器为什么会选择暴雨?
  • Spring Boot + Apache Tika 从文件或文件流中提取文本内容
  • day26|学习前端之算法学习
  • 数据结构之二叉树(2)
  • Mac设置中的安全性缺少“任何来源”
  • 样式化你的 Next.js 应用:CSS 模块、Tailwind CSS 和全局样式
  • Qwen2.5-VL技术详解
  • Claude code 使用笔记
  • FPGA学习笔记——SDR SDRAM的读写(不调用IP核版)
  • C++ 常见面试题汇总
  • cifar10分类对比:使用PyTorch卷积神经网络和SVM