# 代码随想录二刷(哈希表)
代码随想录二刷(哈希表)
三数之和思路反正对于我来说是真的难想出来。
若这道题还是采用哈希表的思路去做,非常麻烦,并且还要考虑去重的操作。所以这道题其实用双指针,是更方便的。
具体程序如下:
class Solution:
def threeSum(self, nums: List[int]) -> 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 right > left:
sum = nums[i] + nums[left] + nums[right]
if sum > 0:right -= 1
elif sum < 0:left += 1
else:
result.append([nums[i],nums[left],nums[right]])
while right > left and nums[right] == nums[right-1]:
right -= 1
while right > left and nums[left] == nums[left+1]:
left += 1
right -= 1
left += 1
return result
下面来看下四数之和:
四数之和相当于三数之和升级了一下,并且target不是0了。按照三数之和的思路,再加一个变量作为外层循环。组合出来四个数即可。
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
result = []
n = len(nums)
nums.sort()
for i in range(n):
if nums[i] > target and target > 0:break
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,n):
if (nums[i] + nums[j]) > target and target > 0:break
if j > i + 1 and nums[j] == nums[j-1]:
continue
left = j + 1
right = n - 1
while right > left:
sum = nums[i] + nums[j] + nums[left] + nums[right]
if sum > target:right -= 1
elif sum < target:left += 1
else:
result.append([nums[i],nums[j],nums[left],nums[right]])
while right > left and nums[right] == nums[right-1]:
right -= 1
while right > left and nums[left] == nums[left+1]:
left += 1
right -= 1
left += 1
return result
本文来自博客园,作者:Bathwind_W,转载请注明原文链接:https://www.cnblogs.com/bathwind/p/18335584