hash table

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 18:54   1035   0

Easy:

happy number: https://leetcode.com/problems/happy-number/

如果结果存在非1的循环,则不是happy number,所以可以通过检查结果是否存在循环来判断。一个可用的cycle detection算法是Floyd algorithm(也叫Tortoise and hare algorithm)。思想是设置两个指针p1,p2。p1一次移动一个单位,p2一次移动两个单位,当p1 == p2时表示循环出现。如果此时的值是1,则返回true,否则返回false。算法详情参考https://en.wikipedia.org/wiki/Cycle_detection,实现详情参考https://leetcode.com/discuss/33055/my-solution-in-c-o-1-space-and-no-magic-math-property-involved

这道题还有一个解法就是用hash table,不断计算下一个值,检查这个值在hash table中是否存在,如果不存在则插入;如果存在检查结果是不是1,如果是1则返回true,否则返回false

isomorphic strings: https://leetcode.com/problems/isomorphic-strings/

定义两个256长度的数组并初始化为0,同时遍历两个字符串,每次先检查当前字符上一次出现的位置是否相同,若不同返回false,若相同则更新该字符的出现位置

(Word Pattern(https://leetcode.com/problems/word-pattern/)同理,不过hash table变成了<string, int>和<char, int>)

Medium:

Repeated DNA Sequence: https://leetcode.com/problems/repeated-dna-sequences/

因为只有ATCG四种可能,所以可以用2'b00, 2'b01, 2'b10和2'b11分别代表。使用一个int变量作为hash table的index,

index = index << 2 | getIndex(s[i]) & 0xfffff,当在hash table中对应的值是1时将序列放入结果(0xffff是20个1'b1,20=10*2)

Two Sum: https://leetcode.com/problems/two-sum/

将nums[i]作为key,遍历nums,先检查(target - nums[i])作为key在hash table中是否存在,如果存在则已找到结果,如果不存在则将{nums[i], i + 1}插入hash table

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP