三数字想加等于0 性能 O(N^2)
public class ThreeSum {
public static void main(String[] args) {int[] nums = {-1,0,1,6,-2,-4};
System.out.println(threeSum1(nums).toString());
}
public static ArrayList<Atem> threeSum1(int[] num) {
ArrayList<Atem> result = new ArrayList<Atem>();
if (num.length < 3)
return result;
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
//avoid duplicate solutions
if (i == 0 || num[i] > num[i - 1]) {
int negate = -num[i];
int start = i + 1;
int end = num.length - 1;
while (start < end) {
//case 1
if (num[start] + num[end] == negate) {
ArrayList<Integer> temp = new ArrayList<Integer>();
Atem atem = new Atem(num[i], num[start], num[end]);
result.add(atem);
start++;
end--;
//avoid duplicate solutions
while (start < end && num[end] == num[end + 1])
end--;
while (start < end && num[start] == num[start - 1])
start++;
//case 2
} else if (num[start] + num[end] < negate) {
start++;
//case 3
} else {
end--;
}
}
}
}
return result;
}
}
class Atem{
private int num1;
private int num2;
private int num3;
public Atem(int num1,int num2,int num3){
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
@Override
public String toString() {
return "Atem [num1=" + num1 + ", num2=" + num2 + ", num3=" + num3 + "]";
}
}