454.四数相加 II
利用字典存入nums1和nums2的各元素之和及其出现次数,再计算nums3和nums4的各元素之和的相反数,检查是否与nums1和nums2中的元素和为相反数
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
sum12 = {}
for i in nums1:
for j in nums2:
if i + j in sum12:
sum12[i + j] += 1
else:
sum12[i + j] = 1
count = 0
for i in nums3:
for j in nums4:
if -i-j in sum12:
count += sum12[-i-j]
return count
383. 赎金信
我的答案:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dic_r = {}
for i in ransomNote:
if i in dic_r:
dic_r[i] += 1
else:
dic_r[i] = 1
dic_m = {}
for i in magazine:
if i in dic_m:
dic_m[i] += 1
else:
dic_m[i] = 1
for i in dic_r.keys():
if i in dic_m and dic_r[i] <= dic_m[i]:
continue
else:
return False
return True
参考答案:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
counts = {}
for c in magazine:
counts[c] = counts.get(c, 0) + 1
for c in ransomNote:
if c not in counts or counts[c] == 0:
return False
counts[c] -= 1 #c所指代的字母使用次数-1
return True
字典的get函数可以替代判断变量是否在dict.key之内而后添加key或者增加value的语句
15. 三数之和
利用双指针,i在左,right在右,left在中间移动
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return res
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = len(nums) - 1
while right > left:
sum = nums[i] + nums[left] + nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else:
res.append([nums[i], nums[left], nums[right]])
while right > left and nums[right] == nums[right - 1]:
right -= 1
while right > left and nums[left] == nums[left + 1]:
left += 1
right -= 1
left += 1
return res
18. 四数之和
在上一题的基础上增加了一层嵌套,同样利用双指针,i在左,而后j,left移动,right在右
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n):
if nums[i] > target and nums[i] > 0 and target > 0:
break
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, n):
if nums[i] + nums[j] > target and target > 0:
break
if j > i+1 and nums[j] == nums[j-1]:
continue
left, right = j+1, n-1
while left < right:
s = nums[i] + nums[j] + nums[left] + nums[right]
if s == target:
result.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
elif s < target:
left += 1
else:
right -= 1
return result
参看文献:代码随想录