# 242. 有效的字母异位词
- 链接:https://www.bilibili.com/video/BV1YG411p7BA/
- 第一想法:
分别遍历s和t,得到相对应的dictonary,key是字母,value是出现的次数。
如果俩dictionaries相同,则为异位词。
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_dict = {}
t_dict = {}
for i in s:
s_dict[i] = s_dict.get(i,0) + 1
for i in t:
t_dict[i] = t_dict.get(i,0) + 1
return dict(sorted(s_dict.items()))==dict(sorted(t_dict.items()))
- 看完代码随想录的想法:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
hash = [0]*26
for i in range(len(s)):
hash[ord(s[i])-ord('a')] += 1 # return the Unicode code from a given character
for j in range(len(t)):
hash[ord(t[j])-ord('a')] -= 1
for k in range(26):
if hash[k] != 0:
return False
return True
# 349. 两个数组的交集
- 链接:https://www.bilibili.com/video/BV1ba411S7wu/
- 第一想法:
用set保留list里面unique的值。然后看有哪些重合的elements
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
- 看完代码随想录的想法:
先遍历nums1,以dictonary记录每个数字是否出现;再遍历nums2,如果有元素即在nums1也在nums2,则放进ans;为了去重,要把已经放进ans的元素 所对应在nums1_dict的value变成0。
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1_dict = {}
ans = []
for num in nums1:
nums1_dict[num] = nums1_dict.get(num,1)
for num in nums2:
if num in list(nums1_dict.keys()) and nums1_dict[num] == 1:
ans.append(num)
nums1_dict[num] = 0
return ans
# 202. 快乐数
- 链接:https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html
- 第一想法:不知道怎么做
- 看完代码随想录的想法:
题目关键在于:无限循环
可以用哈希表存每次的平方和,如果有重复的值,就证明有循环。
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def get_sum(n):
total = 0
while n>=1:
total += (n%10)**2
n = n/10
return total
sum_dict = {}
while (n!=1):
n = get_sum(n)
sum_dict[n] = sum_dict.get(n,0) + 1
if sum_dict[n] > 1:
return False
return True
# 1. 两数之和
- 链接:梦开始的地方,Leetcode:1.两数之和,学透哈希表,map使用有技巧!_哔哩哔哩_bilibili
- 第一想法:
可以用哈希表存储index。
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
# """
# records = dict()
# # 用枚举更方便,就不需要通过索引再去取当前位置的值
# for idx, val in enumerate(nums):
# if target - val not in records:
# records[val] = idx
# else:
# return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
nums_dict = {}
for idx,val in enumerate(nums):
if target-val not in nums_dict:
nums_dict[val] = idx
else:
return [nums_dict[target-val],idx]
- 看完代码随想录的想法:
之前刷过这个题,所以做法是一样的