给定一个包含 n 个整数的数组?nums,判断?nums?中是否存在三个元素?a ,b ,c ,使得?a + b + c = 0 ?请找出所有和为 0 且?不重复?的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 示例 2:
输入:nums = [] 输出:[] 示例 3:
输入:nums = [0] 输出:[]
提示:
0 <= nums.length <= 3000 -10^5 <= nums[i] <= 10^5
java代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
int lg = nums.length;
Arrays.sort(nums);
for (int i = 0; i < lg; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = lg - 1;
while (left < right) {
int total = nums[i] + nums[left] + nums[right];
if (total == 0) {
ans.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
left++;
} else if (total < 0) left++;
else if (total > 0) right--;
}
}
return ans;
}
}
|