task1.python实现三数之和,(正整数)
class threesum:
def threeSum(self, nums):
if len(nums) < 3:
return []
nums.sort()
last_number = None
result = []
for i in range(0, len(nums)-2):
if nums[i] > 0:
break
elif nums[i] == last_number:
continue
l = i+1
r = len(nums)-1
while l < r:
cur_sum = nums[i] + nums[l] + nums[r]
if cur_sum < 0:
l += 1
elif cur_sum > 0:
r -= 1
else:
result.append([nums[i], nums[l], nums[r]])
while l<r and nums[l] == nums[l+1]:
l += 1
while l<r and nums[r] == nums[r-1]:
r -= 1
l += 1
last_number = nums[i]
return result
网友评论