383. 赎金信
题目链接:https://leetcode.cn/problems/ransom-note/
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
arr = [0] * 26
for i in magazine:
arr[ord(i) - ord('a')] += 1
for i in ransomNote:
if arr[ord(i) - ord('a')] == 0:
return False
else:
arr[ord(i) - ord('a')] -= 1
return True
454. 四数相加II
题目链接:https://leetcode.cn/problems/4sum-ii/
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
if n1+n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
count = 0
for n3 in nums3:
for n4 in nums4:
if -n3-n4 in hashmap:
count += hashmap[-n3-n4]
return count
18.四数之和
题目链接: https://leetcode.cn/problems/4sum/
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n):
if i >= 1 and nums[i] == nums[i-1]:
continue
for k in range(i+1, n):
left, right = k+1, n-1
if k > i+1 and nums[k] == nums[k-1]:
continue
while left < right:
total = nums[i] + nums[k] + nums[left] + nums[right]
if total < target:
left += 1
elif total > target:
right -= 1
else:
res.append([nums[i],nums[k],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
15. 三数之和
题目链接:https://leetcode.cn/problems/3sum/
思路和上题一模一样
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
n = len(nums)
nums.sort()
for i in range(n):
left, right = i+1, n-1
if nums[i] > 0:
break
if i >= 1 and nums[i] == nums[i-1]:
continue
while left < right:
total = nums[i] + nums[left] + nums[right]
if total > 0:
right -= 1
elif total < 0:
left += 1
else:
ans.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
left += 1
right -= 1
return ans