语言为Python
454.四数相加
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap={}
for i in nums1:
for j in nums2:
if i+j in hashmap:
hashmap[i+j]+=1
else:
hashmap[i+j]=1
count=0
for k in nums3:
for l in nums4:
key = -k-l
if key in hashmap:
count+=hashmap[key]
return count
383. 赎金信
思路:
判断 ransomNote
能不能由 magazine
里面的字符构成。
如果可以,返回 true
;否则返回 false
。
的意思就是ransomnote是不是magazine的子字符串(这里的ransomnote与magazine的字母都是小写字母 不用辨别大小写)用
for i in magazine:
hashmap[i]=hashmap.get(i,0)+1
来让magazine的元素添加到hashmap里面
然后用for遍历ransomnote的元素 并判断是否在hashmap中 或其元素对应的数量为0 则return False 每一次判断都需要使hashmap[i]-=1
最后return True
下面是代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap={}
for i in magazine:
hashmap[i]=hashmap.get(i,0)+1
for i in ransomNote:
if i not in hashmap or hashmap[i]==0:
return False
hashmap[i]-=1
return True
15. 三数之和
思路:我们这里可以采用双指针 然后用for遍历的办法来判断 首先我们可以用nums.sort()来排序列表 如果列表的第一个元素就已经大于0了 那么这个列表就不可能存在三个数相加等于0的情况 所以就可以直接返回一个空列表 因为我们需要让left一直右移 所以用while left<right 让total为三数的总和 如果total为0 则用res.append来添加 用这个代码来判断是否存在有相同的元素
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
最后return res即可
下面是代码
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
if nums[0] > 0:
return []
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
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] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return res
● 18. 四数之和
思路:这个题与上面的题相似 我们采用双指针的话只是多了一个for来遍历 于是不过多介绍了
下面是代码
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
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
res.append([nums[i], nums[j], 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
elif total < target:
left += 1
else:
right -= 1
return res