马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,n):#j的遍历从i的下一位置开始
if j > i + 1 and nums[j] == nums[j-1]:
continue
l = j + 1
r = n - 1
while l < r:
if r < n - 1 and nums[r] == nums[r+1]:
r -= 1
elif l > j + 1 and nums[l] == nums[l-1]:
l += 1
elif nums[i] + nums[j] + nums[l] + nums[r] == target:
res.append([nums[i], nums[j], nums[l], nums[r]])
r -= 1
l += 1
elif nums[i] + nums[j] + nums[l] + nums[r] > target:
r -= 1
else:
l += 1
return res
上述代码求的是四数之和,写成以下代码的话有什么区别class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,n):#j的遍历从i的下一位置开始
if j > i + 1 and nums[j] == nums[j-1]:
continue
l = j + 1
r = n - 1
while l < r:
if r < n - 1 and nums[r] == nums[r+1]:
r -= 1
if l > j + 1 and nums[l] == nums[l-1]:
l += 1
if nums[i] + nums[j] + nums[l] + nums[r] == target:
res.append([nums[i], nums[j], nums[l], nums[r]])
r -= 1
l += 1
elif nums[i] + nums[j] + nums[l] + nums[r] > target:
r -= 1
else:
l += 1
return res
|