一。 今日学习的文章链接和视频链接
- day 7 任务以及具体安排:第三章 哈希表part02 (10.17)
454.四数相加II
383. 赎金信
15. 三数之和
18. 四数之和
二。 自己看到题目的第一想法
454.四数相加II
暴力解法可以脑内想通。
383. 赎金信
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = Counter(magazine)
for s in ransomNote:
if s in hashmap and hashmap[s] > 0:
hashmap[s] -= 1
else:
return False
return True
15. 三数之和
想到了排序,和三个指针,但没有想通顺指针在哪里怎么移动 --> idx: i, left, right
18. 四数之和
思路正确,比3sum 多一个for循环
三。 看完代码随想录之后的想法
454.四数相加II
本题是使用哈希法的经典题目, 这道题目是四个独立的数组,只要找到A[i] + B[j] + C[k] + D[l] = 0就可以,不用考虑有重复的四个元素相加等于0的情况,所以相对于题目18. 四数之和,题目15.三数之和,还是简单了不少!
result incremented by what value!!!
可以避免import collections from defaultdict,
hashmap[n1+n2] = hashmap.get(n1+n2, 0) + 1
383. 赎金信
Counter的奇妙用法,可以直接 -
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return not (Counter(ransomNote) - Counter(magazine))
usage of 'all'
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_count = [0] * 26
magazine_count = [0] * 26
for c in ransomNote:
ransom_count[ord(c) - ord('a')] += 1
for c in magazine:
magazine_count[ord(c) - ord('a')] += 1
return all(ransom_count[i] <= magazine_count[i] for i in range(26))
15. 三数之和
两数之和 就不能使用双指针法,因为1.两数之和 (opens new window)要求返回的是索引下标, 而双指针法一定要排序,一旦排序之后原数组的索引就被改变了。
去重逻辑的思考
记得刷第一遍的时候绕了好久,重要内容!
submit两次还是去重没有思考清楚,不得不去上班了,已经11:36am。。
去重很重要,做4sum时第一次run test没过就是因为重复。i, left, right, 三个指针,i的去重,left/right在找到 == target时的去重
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
res = []
i = 0
for i in range(len(nums) - 2): # 一开始用while, 但处理需continue的那里i++比较麻烦
if nums[i] > 0:
return res
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
if (nums[i] + nums[left] + nums[right]) > 0:
right -= 1
elif (nums[i] + nums[left] + nums[right]) < 0:
left += 1
else:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
right -= 1
left += 1
i += 1
return res
18. 四数之和
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums)):
subsum = target - nums[i]
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, len(nums)):
left, right = j+1, len(nums) - 1
if j > i+1 and nums[j] == nums[j-1]:
continue
while left < right:
total = nums[j] + nums[left] + nums[right]
if total < subsum:
left += 1
elif total > subsum:
right -= 1
else:
res.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return res