Daily LeetCode 15. 3Sum

https://leetcode.com/problems/3sum/

Medium

问题描述

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

1
2
3
4
5
6
7
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

思路及代码

这一题要求从一个数组中找三个数,确保三个数的和为零,返回所有的和为零的三个数组成的数组。

首先,我们对数组进行排序,对升序数组进行遍历,在遍历过程中,我们使用双指针寻找另外两个数。

如果当前遍历到的数大于零,我们可以结束遍历,因为此时数组是升序的,三个正数的和不可能为零;如果当前遍历到的数与前一个数相等,那么就跳过这个数,因为结果需要删除重复结果。

假设当前遍历到了nums[i],我们设置左指针left_index=i+1, right_index=len(nums)-1,当前sum = nums[i] + nums[left_index] + nums[right_index],此时根据sum的情况进行下一步操作:

  • sum>0:说明当前取的正数偏大,将右指针左移
  • sum<0:说明当前取的负数偏小,将左指针右移
  • sum=0:将当前三个数加入结果,并且将左右指针移到没有重复元素的位置

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if nums[i] > 0: break
if i > 0 and nums[i] == nums[i - 1]: continue
left_index, right_index = i + 1, len(nums) - 1
while left_index < right_index:
sum = nums[i] + nums[left_index] + nums[right_index]
if sum > 0:
right_index -= 1
elif sum < 0:
left_index += 1
else:
res.append([nums[i], nums[left_index], nums[right_index]])
while left_index < right_index and nums[left_index + 1] == nums[left_index]:
left_index += 1
while left_index < right_index and nums[right_index - 1] == nums[right_index]:
right_index -= 1
left_index += 1
right_index -= 1
return res