
思路:看看哈希表是不是一样就可以,for循环遍历,把内容加到defaultdict里面
主要还是熟练度问题吧,字典平时写的比较少,取键取值再看看
python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_str = defaultdict(int)
for i in s:
s_str[i] += 1
for j in t:
s_str[j] -= 1
for val in s_str.values():
if val != 0:
return False
return True

思路:相似,用defaultdict获取nums1中的所有值,如果nums2中的数在dic中,加到集合里,最后返回list形式的集合即可
python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = defaultdict(int)
res = set()
for i in nums1:
dic[i] += 1
for j in nums2:
if dic[j] != 0:
res.add(j)
return list(res)

没啥思路啊,看上去有点复杂,写个分解函数?还真是,确实简单,写个分解函数。吧n转化成一个个数字再平方和的sum_new,如果函数生成不是1,加入集合就一直循环,直到生成的数再给定的集合里
python
class Solution:
def isHappy(self, n: int) -> bool:
ans = set()
while self.getnew(n) != 1:
if self.getnew(n) in ans:
return False
ans.add(self.getnew(n))
n = self.getnew(n)
return True
def getnew(self, n):
res = []
sum_new = 0
while n != 0:
num = n%10
n //= 10
res.append(num)
for i in res:
sum_new += i**2
return sum_new

思路:遍历一遍数组,同步的保存target-nums[i],如果遇到相同的数即返回这个结果数组,注意,这里返回的是索引,应该是此刻遍历到的i,以及nums[i]对应的值
null
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = defaultdict(int)
res = []
for i in range(len(nums)):
if nums[i] in dic:
res.append(i)
res.append(dic[nums[i]])
break
else:
dic[target-nums[i]] = i
return res

思路:for循环遍历1,2数组的所有和,负值加入到字典里;再for循环遍历3,4数组的和,如果in字典,加上字典的值即可。
null
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
dic = defaultdict(int)
for i in nums1:
for j in nums2:
dic[-i-j] += 1
count = 0
for p in nums3:
for q in nums4:
if p+q in dic:
count += dic[p+q]
return count

思路:遍历magazine中的所有字母,放到字典里,然后用ransomnote取用,如果取用时发现值为0,则返回false
python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dic = defaultdict(int)
for i in magazine:
dic[i] += 1
for j in ransomNote:
if dic[j] == 0:
return False
dic[j] -= 1
return True

思路:题意也即该数组内所有的数不能重复使用,但是可以允许数字相同。考虑首先遍历数组,获取-(nums i+ nums j),并保存在字典里,值为【i,j】,如果nums k in字典,查k在不在【i,j】中,如果不在,append然后加到结果数组里面。
这个思路有问题:对于同一个-(nums i+ nums j),回复该前面的而数组,而且这里要加入的是三元组
采用思路:
1:去重:也即防止使用了相同位置的数
2:用-nums[i]-nums[j]来表示第三个数。因为第三个数肯定在j的遍历过程中,只需再所有的j中遍历即可,因为先判断再输出,这里不存在重合的情况,也即j不会和c选到同一个数。
null
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
nums.sort()
res = set()
for i in range(len(nums)-2):
if i>0 and nums[i] == nums[i-1]:
continue
seen = set()
for j in range(i+1, len(nums)):
c = -nums[i]-nums[j]
if c in seen:
res.add(tuple((nums[i],c,nums[j])))
seen.add(nums[j])
return [list(tup) for tup in res]