三数之和
题目描述
给你一个包含 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]
输出:[]
思路
两数之和的变种,最内层2个数可以用双指针,这样时间复杂度可以降低1次。
算法
1.对nums排序
2.遍历nums,作为first
3.second 和 third 一个从first.next往右,third从末尾往左。
4.得到结果list
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
int length = nums.length;
if (length<3){
return list;
}
if (length ==3){
if (nums[0]+nums[1]+nums[2]==0){
List<Integer> t = new ArrayList<Integer>();
t.add(nums[0]);
t.add(nums[1]);
t.add(nums[2]);
list.add(t);
return list;
}else{
return list;
}
}
Arrays.sort(nums);
for (int i =0; i <length-2;i++){
if (i>0 && nums[i] == nums[i-1]){
continue;
}
int l = i+1,r = length-1;
while(l<r){
if (l>i+1 && nums[l]== nums[l-1]){
l++;
continue;
}
int sum = nums[i]+nums[l] +nums[r];
if (sum == 0){
List<Integer> t = new ArrayList<Integer>();
t.add(nums[i]);
t.add(nums[l]);
t.add(nums[r]);
list.add(t);
l++;
}else if(sum<0){
l++;
}else{
r--;
}
}
}
return list;
}
}
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。