454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和
454.四数相加II
1、本题使用字典做哈希,因为数组适用于有限的数组,然而本地的数组长度不确定;另外,本题需要统计满足条件的元组个数,因此不适合使用集合。
2、为了降低时间复杂度,用两个二层for循环。
3、num1,nums2之和与nums3,nums4之和相反,即nums1 + nums2 + nums3 + nums4 = 0.
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:type nums4: List[int]
:rtype: int
"""
hash_dict = {}
for i in nums1:
for j in nums2:
if (i + j) in hash_dict:
hash_dict[i+j] += 1
else:
hash_dict[i+j] = 1
count = 0
for p in nums3:
for q in nums4:
key = -(p + q)
if key in hash_dict:
count += hash_dict[key]
return count
383. 赎金信
1、本题要注意ransomNote 能不能由 magazine 里面的字符构成。而不是两个字符串里字符一样。
2、先将magazine里的字符用字典统计出,然后再去ransomNote里判断字符是否在magazine里,如果不在就FALSE
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
from collections import defaultdict
hashmap = defaultdict(int)
for i in magazine:
hashmap[i] += 1
for j in ransomNote:
value = hashmap[j]
if value is None or value == 0:
return False
else:
hashmap[j] -= 1
return True
15. 三数之和
1、nums[i-1] == nums[i] : continue 是防止有重复的三元组出现。
2、三元组内可以有重复元素,但是不可以有重复的三元组。
3、本题使用双指针法,指针法一定要排序,一旦排序之后原数组的索引就被改变了。如果返回索引的题目,就不适用排序。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
length = len(nums)
nums.sort()
res = []
for i in range(length):
left = i + 1
right = length - 1
if nums[0] > 0:
break
if i >= 1 and nums[i-1] == nums[i]:
continue
while left < right:
temp_sum = nums[i] + nums[left] + nums[right]
if temp_sum > 0:
right -= 1
elif temp_sum < 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 - 1] == nums[right]:
right -= 1
left += 1
right -= 1
return res
18. 四数之和
1、一定要注意多个循环的下标!!!!!!!!!!!!!!!
2、四数之和在三数之和基础上又增加了一个for循环。
3、剪枝条件有所不同:因为target有可能为负数,因此不能简单的使nums[k] > 0. 一定要在nums[k] > 0 并且 target > 0 的基础上进行剪枝。
4、里面for循环的剪枝要将nums[i] + nums[k]看成一个整体。
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
nums.sort()
length = len(nums)
for k in range(length):
if nums[k] > 0 and nums[k] > target:
break
if nums[k] == nums[k-1] and k > 0:
continue
for i in range(k+1, length):
if nums[i] + nums[k] > 0 and nums[i] + nums[k] > target:
break
if i > k + 1 and nums[i] == nums[i-1]:
continue
left = i + 1
right = length - 1
while left < right:
if nums[k] + nums[i] + nums[left] + nums[right] > target:
right -= 1
elif nums[k] + nums[i] + nums[left] + nums[right] < target:
left += 1
else:
res.append([nums[k], 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 res