一、 题目描述
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a ,b ,c ,使得 a + b + c = 0 ?请找出所有和为 0 且 不重复 的三元组。
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
二 、代码思想
2.1 暴力解法
- 三个for循环嵌套,找出来三个数之和为target即可。
- 需要注意的是遇到不可重复数据的要求,可以考虑使用HashMap集合的特点来做。
- 还需要注意的是:
1、 如何把set转成list(因为你使用set去重,但是最后要用list返回);
2、 以及将list数组元素排序后再加入set(不排序的话即使元素都相同但是顺序不同依旧算是不同的List)
2.2 双指针的操作
针对两数之后我们将排序之后的数组进行双指针的操作,针对三数之和,我们可以在确定一个数的前提之下进行双指针的操作。
值得注意的是:因为可能存在多种结果,所以使用双指针找到一个结果之后还应该继续遍历,直到两个指针重合。
三、 代码求解
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//List<List<Integer>> res=new ArrayList();
Set<List<Integer>> set=new HashSet();
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
for(int k=j+1;k<nums.length;k++){
if(nums[i]+nums[j]+nums[k]==0){
List<Integer> list=new ArrayList();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
Collections.sort(list);
set.add(list);
}
}
}
}
return new ArrayList(set);
}
}
双指针的操作:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> set=new HashSet();
if(nums.length<3) return new ArrayList<List<Integer>>();
Arrays.sort(nums);
System.out.print(Arrays.toString(nums));
for(int i=0;i<nums.length;i++){
int firstPoint= i+1;
int lastPoint= nums.length-1;
while(firstPoint<lastPoint){
int num=0-nums[i];
if(nums[firstPoint]+nums[lastPoint]==(num)){
List<Integer> list=new ArrayList();
list.add(nums[i]);
list.add(nums[firstPoint]);
list.add(nums[lastPoint]);
set.add(list);
firstPoint++;
}else if(nums[firstPoint]+nums[lastPoint]<num){
firstPoint++;
continue;
}else if(nums[firstPoint]+nums[lastPoint]>num){
lastPoint--;
continue;
}
}
}
return new ArrayList(set);
}
}
时间复杂度:O(n2)