15. 三数之和
难度:
中等
描述:
给定一个包含 n 个整数的数组
nums
,判断nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:
答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
代码实现:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int leftIdx = i + 1;
int rightIdx = nums.length - 1;
while (leftIdx < rightIdx) {
int sum = nums[leftIdx] + nums[rightIdx] + nums[i];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[leftIdx++], nums[rightIdx--]));
while (leftIdx < rightIdx && nums[leftIdx] == nums[leftIdx - 1]) ++leftIdx;
while (leftIdx < rightIdx && nums[rightIdx] == nums[rightIdx + 1]) --rightIdx;
} else if (sum < 0) {
++leftIdx;
} else {
--rightIdx;
}
}
}
return result;
}
}