454.四数相加II
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路 :
先给num1和num2遍历的合还有合出现的次数建立一个map,然后遍历nums3,nums4,如果其中有(0-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
"""
#set up hashtable for nums1 and nums2
hashtable_1={}
for num_1 in nums1:
for num_2 in nums2:
if num_1 + num_2 in hashtable_1:
hashtable_1[num_1 + num_2] += 1
else:
hashtable_1[num_1 + num_2] = 1
result = 0
for num_3 in nums3:
for num_4 in nums4:
if 0 - num_3 - num_4 in hashtable_1:
result += hashtable_1[0 - num_3 - num_4]
return result
- 时间复杂度 O(n^2)
- 空间复杂度 O(n)
383. 赎金信
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解:代码随想录
解题思路:
给magazine遍历一遍个数
再遍历ransomnote
如果letter 没出现return false
出现就减magazine里的次数 此时小于0那说明False
成功遍历则return ture
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
#set up dic for ransomNote
dic_mag={}
for letter in magazine:
if letter in dic_mag:
dic_mag[letter]+=1
else:
dic_mag[letter]=1
for letter in ransomNote:
if letter in dic_mag:
dic_mag[letter]-=1
if dic_mag[letter]<0:
return False
else:
return False
return True
- 时间复杂度 O(n)
- 空间复杂度 O(1) 因为字母只有26个
15. 三数之和
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
有点复杂,尽量解释。。
双指针
首先sort,方便遍历双指针。
设置左右指针
遍历i
第一个数字直接大于0了就不需要继续遍历了 因为是升序排序。
同时注意查重这个i的数字,如果他与i-1相同那就不需要再次跑了 直接continue。
然后进行双指针的遍历(condition为left<right),如果total>0移动右指针-1,total<0移动左指针+1,如果等于的话记录答案并注意查重b和c。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result=[]
n=len(nums)
for i in range(n):
left=i+1
right=n-1
if nums[i]>0:
break
if i >0 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:
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
- 时间复杂度 O(n^2)
- 空间复杂度 O(1)
18. 四数之和
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result=[]
n=len(nums)
for i in range(n):
if i > 0 and nums[i]==nums[i-1]:
continue
for j in range(i+1,n):
if j > i + 1 and nums[j]==nums[j-1]:
continue
left=j+1
right=n-1
while left<right:
total=nums[i]+nums[j]+nums[left]+nums[right]
if total > target:
right-=1
elif total < target:
left += 1
else:
result.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
return result
- 时间复杂度 O(n^3)
- 空间复杂度 O(1)