题目描述
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题思路
转换为 2Sum 问题。target 为-nums[i]。
代码
class Solution {
List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length < 3)
return ret;
Arrays.sort(nums);
for (int i = 0; i < nums.length-2; i++) {
if (i > 0 && nums[i] == nums[i-1])
continue;
twoSum(nums, i+1);
}
return ret;
}
private void twoSum(int[] nums, int start) {
int left = start;
int right = nums.length-1;
while (left < right) {
if (nums[left] + nums[right] + nums[start-1] == 0) {
ArrayList<Integer> list = new ArrayList<>();
list.add(nums[start-1]);
list.add(nums[left]);
list.add(nums[right]);
ret.add(list);
while (left < right && nums[left] == nums[left+1])
left++;
while (left < right && nums[right] == nums[right-1])
right--;
left++;
right--;
} else if (nums[left] + nums[right] + nums[start-1] < 0) {
left++;
} else if (nums[left] + nums[right] + nums[start-1] > 0)
right--;
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于