代码随想录第五天|第三章 哈希表 I

本文介绍了哈希表的基础知识,包括其作为直接访问数据结构的角色,以及在快速查找和计数中的应用。哈希函数是关键,它将任意大小的数据映射到固定大小的值,用于索引哈希表。讨论了哈希碰撞及其解决方法,如拉链法和线性探测法。并提供了相关题目链接以加深理解。
摘要由CSDN通过智能技术生成

 I#Java、#哈希表、#数组

一、今日学习链接

        1、哈希表理论基础,文章链接

        2、242. Valid Anagram,文章链接,视频链接

        3.  349. Intersection of Two Arrays,文章链接,视频链接

        4、202. Happy Number,文章链接

二、哈希表理论知识(摘自上述文章链接)

        哈希表(英文名字为Hash table,国内也有一些算法书籍翻译为散列表,大家看到这两个名称知道都是指hash table就可以了)。

        哈希表是根据关键码的值而直接进行访问的数据结构。哈希表中关键码就是数组的索引下标,然后通过下标直接访问数组中的元素。

        哈希表的用途:用来快速判断一个元素是否出现集合里、计数(HashMap)。

        哈希函数(散列函数): A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash valueshash codesdigests, or simply hashes. The values are usually used to index a fixed-size table called a hash table. Use of a hash function to index a hash table is called hashing or scatter storage addressing. (Wikipedia)

        哈希碰撞 (Hash Collision):拉链法和线性探测法。In computer science, a hash collision or clash[citation needed] is when two pieces of data in a hash table share the same hash value. The hash value in this case is derived from a hash function which takes a data input and returns a fixed length of bits. Probability of occurrence: CRC-32, MD5, SHA-1. Collision resolution: Open addressing, Separate chaining, Cache-conscious collision resolution. (Wikipedia)

三、解题思路

题号思路相关主题难度
242. Valid Anagram

方法一:Arrays.sort();

要用吧sort之后的数组单独保存下来,否则比较大时候还是之前的数组

方法二:HashMap

这个题如果不把map的value(这里是size)单独提炼出来,会有个case跑不过。需要int count1 = map2.get(c);

如果map的size超过128,对于size作为Integer不是primitive,如果value小于128,比较value。如果value大于128比较的则是reference,int count1 = map2.get(c);->将Integer转换成int进行比较。

HashMap

Arrays.sort();

easy
349. Intersection of Two Arrays

关键词:intersection, unique, any order

HashSet去重,查相交

HashSeteasy
202. Happy Number

关键词:题目中说了会 无限循环,那么也就是说求和的过程中,sum会重复出现,这对解题很重要!

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

还有一个难点就是求和的过程,如果对取数值各个位上的单数操作不熟悉的话,做这道题也会比较艰难。

HashSet

每位数平方后求和

easy
//​202. Happy number
//每一位数平方后累加求和代码
public int getSum(int n){
        int sum = 0;
        while(n > 0){
            int temp = n % 10;
            sum += temp * temp;
            n = n / 10;
        }
        return sum;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值