Leetcode 242 Valid Anagram
- 题目链接:leetcode.com/problems/va…
- 文章讲解:代码随想录 programmercarl.com
- 视频讲解:学透哈希表,数组使用有技巧!Leetcode:242.有效的字母异位词
- 状态:有做出来
1. 第一想法
排序两个 string,然后对比是否一致。我知道这次是要用 hash table 但是这应该还要统计字母的出现次数,我不太知道怎么搞。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s1 = sorted(s)
t1 = sorted(t)
if s1 == t1:
return True
else:
return False
2. 看完后想法
使用一个 size 为26的数组的思路很巧妙。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
record = [0] * 26
for i in s:
record[ord(i) - ord('a')] += 1
for i in t:
record[ord(i) - ord('a')] -= 1
for i in range(26):
if record[i] != 0:
return False
return True
3. 总结
不太有 hash 问题可以用数组的思路,以后可以多往这个方向考虑。
Leetcode 349 Intersection of Two Arrays
- 题目链接:leetcode.com/problems/in…
- 文章讲解:代码随想录 programmercarl.com
- 视频讲解:学透哈希表,set使用有技巧!Leetcode:349. 两个数组的交集
- 状态:没做出来
1. 第一想法
这个是要用 sliding window 吗,但是我还是不会写。
2. 看完后想法
呃....
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
3. 总结
我还是觉得这个题目的描述很费解.....
Leetcode 202 Happy Number
- 题目链接:leetcode.com/problems/ha…
- 文章讲解:代码随想录 programmercarl.com
- 状态:没做出来
1. 第一想法
感觉是不是那种数学类,就是这个数字的出现会有规律?但感觉和 hash 没什么关系啊。
2. 看完后想法
class Solution:
def isHappy(self, n: int) -> bool:
record = set()
while True:
n = self.get_sum(n)
if n == 1:
return True
if n in record:
return False
else:
record.add(n)
def get_sum(self,n: int) -> int:
new_num = 0
while n:
n, r = divmod(n, 10)
new_num += r ** 2
return new_num
3. 总结
以后要仔细观察题目条件。没注意到 loops endlessly in a cycle。
Leetcode 1 Two Sum
- 题目链接:leetcode.com/problems/tw…
- 文章讲解:代码随想录 programmercarl.com
- 视频讲解:梦开始的地方,Leetcode:1.两数之和,学透哈希表,map使用有技巧!
- 状态:有暴解出来
1. 第一想法
这题不管遇到多少次,我都只会暴解。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
return []
2. 看完后想法
这下终于明白为什么用 hash map 了,是为了存储遍历过的。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
for index, value in enumerate(nums):
if target - value in records:
return [records[target - value], index]
records[value] = index
return []
3. 总结
常看常新。