题目:给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum
这道题和力扣第一个题有相似之处。第一题是在数字中找一个target,看存在不存在两个数的值等于等于这个target,那道题是拿每一个数和后边的其他的数字进行组合,看有没有等于target的,满足即可,想一下,在这里,target就变了一下,如果两个数的和等于负的target,即可满足题意
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}
思路是这样的,先将数组进行排序,寻找三个数的和是0,转变为对每一个数寻找有没有两个数的和等于这个数的相反数,如果满足的话,就是用list将这个三个数存起来,寻找两个数相加和时使用双指针遍历,
这里注意题目要求不使用重复值,所以要注意当数组两个相邻的数相等时,直接跳过。
另外对每一个进行查找时也要注意相同的值直接跳过。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int target=0;
Arrays.sort(nums);//先排序
List<List<Integer>> ans = new ArrayList<>();
int l, r;
for (int i = 0; i < nums.length; i++) {
if(i>0&&nums[i]==nums[i-1]) continue;
target = 0 - nums[i];//从后边找这个数字 主要看有没有两数和是这个目标
l = i + 1;
r = nums.length-1;
while (l < r) {
if (nums[l] + nums[r] == target) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[l]);
temp.add(nums[r]);
ans.add(temp);
while(l<r && nums[l]==nums[l+1]) l++;
while(l<r && nums[r]==nums[r-1]) r--;
l++;
r--;
}else if(nums[l]+nums[r]<target){
l++;
}else {
r--;
}
}
}
return ans;
}
}