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 values, hash codes, digests, 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去重,查相交 | HashSet | easy |
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;
}