454.四数之和2
要善用哈希表和Counter,时间复杂度O(n2)。
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
cnt = Counter([x+y for x in nums1 for y in nums2])
return sum(cnt[-x-y] for x in nums3 for y in nums4)
383 赎金信
简单题,秒解~
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
cnt = Counter(list(magazine))
for j in list(ransomNote):
cnt[j] -= 1
for val in cnt:
if cnt[val] < 0:
return False
return True
15.三数之和
看了题解自己写的。这道题是热门题,要及时复习!!注意边界条件。
看这道题之前,先看一下【167.两数之和2】这道题,排序后做法一样,
注意:要跳过重复的数字。不能先通过set操作,因为比如[-1,-1,2]这种情况下,确实某些数字要被使用2次。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted((nums))
res = []
for i in range(len(nums)-2):
if i >0 and nums[i] ==nums[i-1]:
continue
j = i + 1
k = len(nums) - 1
while j < k:
s = nums[i] + nums[j] + nums[k]
if s == 0:
res.append([nums[i],nums[j],nums[k]])
while (j+1)<=(len(nums)-2) and nums[j] == nums[j+1]:
j+= 1
j += 1
while k-1>=0 and nums[k] == nums[k-1]:
k-=1
k -= 1
elif s > 0:
k -= 1
else:
j += 1
return res
18.四数之和
18.四数之和:三数之和的升级版,在三数之和外面套一个循环,其他不变
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n-3):
if i>0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,n-2):
if j>i+1 and nums[j] == nums[j-1]:
continue
k = j + 1
l = n - 1
while k < l:
s = nums[i] + nums[j] + nums[k] + nums[l]
if s > target:
l -= 1
elif s < target:
k += 1
else:
res.append([nums[i],nums[j],nums[k],nums[l]])
k += 1
while k <l and nums[k] == nums[k-1]:
k+=1
l -= 1
while k<l and nums[l] == nums[l+1]:
l -= 1
return res