Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
这道题看起来很简单,但是我遇到了一个奇怪的问题
当输入[-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]的时候,并没有[0,0,0]这个答案出来。下面是我的代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> solutions = new ArrayList<>();
boolean isDuplicate = false;
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)
{
isDuplicate = false;
List<Integer> solution = new ArrayList<>();
solution.add(nums[i]);
solution.add(nums[j]);
solution.add(nums[k]);
for(List<Integer> so : solutions)
{
if(so.containsAll(solution))
{
isDuplicate = true;
break;
}
}
if(isDuplicate == false)
{
solutions.add(solution);
}
}
}
}
}
return solutions;
}
}
把代码修改下就会发现
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> solutions = new ArrayList<>();
boolean isDuplicate = false;
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)
{
isDuplicate = false;
List<Integer> solution = new ArrayList<>();
solution.add(nums[i]);
solution.add(nums[j]);
solution.add(nums[k]);
if(nums[i] == 0 && nums[j]==0 && nums[k]==0)
System.out.println(nums[i]+ " " + nums[j]+" " + nums[k] + " a");
for(List<Integer> so : solutions)
{
if(solution.get(0) == 0 && solution.get(1)==0 && solution.get(2)==0)
{
System.out.println(so.get(0)+ " " + so.get(1)+" " + so.get(2) + " e1");
System.out.println(solution.get(0)+ " " + solution.get(1)+" " + solution.get(2) + " e2");
if(so.containsAll(solution))
{
System.out.println("yes");
}
}
if(so.containsAll(solution))
{
if(solution.get(0) == 0 && solution.get(1)==0 && solution.get(2)==0)
System.out.println("w");
isDuplicate = true;
break;
}
}
if(isDuplicate == false)
{
solutions.add(solution);
}
}
}
}
}
return solutions;
}
}
输出
0 0 0 a
-4 1 3 e1
0 0 0 e2
-4 4 0 e1
0 0 0 e2
yes
w
-4,-4,0居然会包含0,0,0,这是为什么?感觉问题应该是出在containsAll()方法这。
自己写多个检测两个集合是否有相同的数即可,虽然这种方面时间复杂的比较高