242.有效的字母异位词
题目链接/文章讲解/视频讲解: 代码随想录
关键:两个字符串中的字母相同
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
#法一
# res = [0] * 26
# for i in s:
# res[ord(i) - ord('a')] += 1
# for j in t:
# res[ord(j) - ord('a')] -= 1
# return res == [0] * 26
#法2
# from collections import defaultdict
# tmp = defaultdict(int)
# cnt = defaultdict(int)
# for i in s:
# tmp[i] += 1
# for j in t:
# cnt[j] += 1
# return tmp == cnt
#法3
from collections import Counter
tmp = Counter(s)
cnt = Counter(t)
return tmp == cnt
349. 两个数组的交集
题目链接/文章讲解/视频讲解:代码随想录
关键:可以使用集合或者数组
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
#法1
return list(set(nums1)&set(nums2))
#法2 数组
tmp = [0] * 1001 #数组的长度最长为1000
res = []
for i in range(len(nums1)):
tmp[nums1[i]] = 1
for i in range(len(nums2)):
if tmp[nums2[i]] == 1:
res.append(nums2[i])
return list(set(res))
1. 两数之和
题目链接/文章讲解/视频讲解:代码随想录
关键:构建字典,key表示元素,value表示索引,字典保存的是遍历过的元素
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#法一
# res = []
# for i in range(len(nums)):
# cnt = target - nums[i]
# ans = nums[i+1:]
# if cnt in ans:
# res.append(i)
# res.append(ans.index(cnt)+i+1)
# return res
#法二两层for循环
# for i in range(len(nums)-1):
# for j in range(i+1,len(nums)):
# if nums[i] + nums[j] == target:
# return [i,j]
#哈希字典
temp_dict = {}
for i in range(len(nums)):
tmp = target - nums[i]
if tmp not in temp_dict.keys():
temp_dict[nums[i]] = i
else:
return [temp_dict[tmp],i]