454.四数之和
遍历两个数组相加,得到的数放到一个集合里,再遍历另外两个数组相加,判断数组里有没有我们想要的元素。如果有,则找到了一个四个元素相加等于0的匹配项。计数加一,统计四元组的数量。
用什么哈希结构:
元素数值可能很大,数组下标可能不够。考虑set或者map,并且还要统计a+b出现的次数,所以用map。
遍历c+d的时候,查看0-(c+d)是否出现在map里面,如果出现了,加上0-(c+d) 键对应的值。
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()
count = 0
for i in nums1:
for j in nums2:
Hash [i+j] = Hash.get(i+j,0)+1
for i in nums3:
for j in nums4:
if -(i+j) in Hash:
count = count + Hash[-(i+j)]
return count
383.赎金信
本题跟上一节有效字母异位词很像,异位词是两个字符串能不能互相组成,本题是单向。
数组法:
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
ransom_count = [0]*26
magazine_count = [0]*26
for i in ransomNote:
ransom_count[ord(i) - ord("a")] +=1
for i in magazine:
magazine_count[ord(i) - ord("a")] +=1
return all (ransom_count[i]<=magazine_count[i] for i in range(26))
15.三数之和
如果用哈希法去重比较困难,所以更推荐使用双指针法。
a+b+c=0
运用双指针法要对数组进行排序,没有要求返回下标,所以可以排序。i 为a,left为b,right为c
排序之后,如果i>0,直接不符合
如何去重?
nums[i]==nums[i+1];nums[i]==nums[i-1]
不一样,第一个式子会忽略有重复元素的元组,但是元组内部是允许有重复的。
另外就是收获结果之后再去重,否则可能遗漏结果。
以下代码不能通过所有测试
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result=[]
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return result
if i > 0 and nums[i] ==nums[i-1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s > 0:
right -=1
elif s < 0:
left +=1
else:
result.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 result
原因找到了 left+=1 和 right-=1 要放入else里面,以下为正确代码
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result=[]
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return result
if i > 0 and nums[i] ==nums[i-1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s > 0:
right -=1
elif s < 0:
left +=1
else:
result.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 result
18.四数之和
四数之和和三数之和一样,用双指针,再增加一层for循环。剪枝操作,考虑复数。