LC454.四数相加II:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = dict()
count = 0
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1 + n2] += 1
else:
hashmap[n1 + n2] = 1
for n3 in nums3:
for n4 in nums4:
key = 0 - (n3 + n4)
if key in hashmap:
count += hashmap[key]
return count
两个for循环,一个遍历前两个数组,一个遍历后两个,在遍历后两个数组时,找到如果 0-(n3+n4) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
LC383. 赎金信:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
res = [0] * 26
for i in magazine:
res[ord(i) - ord('a')] += 1
for i in ransomNote:
if res[ord(i) - ord('a')] == 0:
return False
else:
res[ord(i) - ord('a')] -= 1
return True
两个for循环分别遍历两个字符串,如果在ransomNote中遍历发现未出现在res里,证明时false。
LC15 三数之和:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
n = len(nums)
nums.sort() #先排序!
for i in range(n):
left = i + 1
right = n - 1 #双指针,一个是i的后一位,一个是末尾
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:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left + 1]:
left += 1 #去重第二个数
while left < right and nums[right] == nums[right - 1]:
right -= 1 #去重第三个数
return res
LC18 四数之和:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
res = []
nums.sort()
n = len(nums)
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue # 去重第一个数
for k in range(i + 1, n):
if k > i + 1 and nums[k] == nums[k - 1]:
continue #去重第二个数
left = k + 1
right = n - 1
while left < right:
total = nums[i] + nums[k] + nums[left] + nums[right]
if total > target:
right -= 1
elif total < target:
left += 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
相比于三数之和多加一个对于k的for循环和去重,其余的一样。