454.四数相加II
思路:较为简单,由于4个数分别位于4个数组,不需要考虑重复值,直接用哈希找到对应值即可
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
dict_1 = dict()
dict_2 = dict()
for i in range(len(nums1)):
for j in range(len(nums1)):
n1 = nums1[i] + nums2[j]
if n1 in dict_1:
dict_1[n1] += 1
else:
dict_1[n1] = 1
n2 = nums3[i] + nums4[j]
if n2 in dict_2:
dict_2[n2] += 1
else:
dict_2[n2] = 1
count = 0
for n in dict_1:
if 0-n in dict_2:
count += dict_1[n]*dict_2[-n]
return count
参考文章:代码随想录-454.四数相加II
383. 赎金信
思路:easy,字符串逐字减去即可判断
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
r_count = [0]*26
m_count = [0]*26
for c in ransomNote:
r_count[ord(c)-ord('a')] += 1
for c in magazine:
m_count[ord(c)-ord('a')] += 1
for i in range(26):
if r_count[i] <= m_count[i]:
continue
else:
return False
return True
参考文章:代码随想录-383. 赎金信
15.三数之和
题目链接:15.三数之和-力扣(LeetCode)
思路:用哈希去算最后去重过于复杂,最好在草稿上演算几遍,确保无误,双指针的思路确实很好,通过排序确定顺序,对于每个i, 通过左右指针的移动找到对应的值,需要注意的是如何避免重复值
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
L = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
break
if i > 0 and nums[i]==nums[i-1]:
continue
d = {}
for j in range(i+1, len(nums)):
if j > i+2 and nums[j]==nums[j-1]==nums[j-2]:
continue
c = 0-nums[i]-nums[j]
if c in d:
L.append([nums[i], nums[j], c])
d.pop(c)
else:
d[nums[j]] = j
return L
参考文章:代码随想录-15.三数之和
18.四数之和
题目链接:18.四数之和-力扣(LeetCode)
思路:解法与三数之和相似,需要在外面多一层for循环,同样需要注意去重
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
L = []
for i in range(len(nums)-3):
target2 = target-nums[i]
if i> 0 and nums[i] == nums[i-1]:
continue
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[len(nums) - 3] + nums[len(nums) - 2] + nums[len(nums) - 1] < target:
continue
for j in range(i+1, len(nums)-2):
if j > i+1 and nums[j]==nums[j-1]:
continue
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[len(nums) - 2] + nums[len(nums) - 1] < target:
continue
l = j + 1
r = len(nums)-1
while l < r:
if nums[j]+nums[l]+nums[r] == target2:
L.append([nums[i],nums[j],nums[l],nums[r]])
while l < r and nums[l] == nums[l+1]:
l+=1
l += 1
while l < r and nums[r] == nums[r-1]:
r -= 1
r -= 1
elif nums[j]+nums[l]+nums[r] > target2:
r -= 1
else:
l += 1
return L
参考文章:代码随想录-18.四数之和