LeetCode15. 三数之和
2019-08-07 本文已影响0人
phantom34
题目
题目描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
题解
首先对于数组我们要做一个排序初始化,满足a+b+c=0的情况,假设a,b,c是按从小到大排那么a+b<0 || a<0,所以我们只要在数组中遍历每一个a,然后在a的右侧寻找b和c,因为我们把数组已经排序好了 所以只要把数组从最左l和最右r往中间缩就能找到当前a的所有可能,在缩进时要去除重复项以免最终答案有重复。并且当a+b>0时已经可以结束查找
代码
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
if (i != 0 && nums[i] == nums[i - 1])
continue;
int l = i + 1;
int r = nums.length - 1;
while (l < r) {
if (nums[i] + nums[l] > 0)
break;
if (r < nums.length - 1 && nums[r] == nums[r + 1]) {
r--;
continue;
}
if (l > i + 1 && nums[l] == nums[l - 1]) {
l++;
continue;
}
if (nums[l] + nums[r] + nums[i] == 0) {
lists.add(Arrays.asList(nums[i], nums[l], nums[r]));
l++;
} else if (nums[l] + nums[r] + nums[i] >= 0) {
r--;
} else {
l++;
}
}
}
return lists;
}
结果
