Identify all satisfy the condition a + b + c = 0 will not be repeated triplet.

You contains a n array of integers  nums, determines  nums whether there are three elements a, b, c, so that  A + B + C = 0? Please do not satisfy the conditions you find all duplicate triples.

Note: The answer can not contain duplicate triples.

 

Example:

Given array nums = [-1, 0, 1 , 2, -1, -4], 

meet the requirements of the set of triples as: 
[ 
  [-1, 0, 1], 
  [-1, -1, 2] 
] 

1, to address violence
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
if (nums == null || nums.length < 3) {
return list;
}
Arrays.sort(nums);
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.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return list;
}
But so would exceed the time limit, and has not performed to re- 
2, an improved version of array traversal
List static public <List <Integer >> threeSum (int [] the nums) { 
List <List <Integer List the ArrayList = new new >> <> ();
IF (nums.length the nums == null || <. 3) return List;
// number of all first array in ascending order
Arrays.sort (the nums);
for (int I = 0; I <nums.length; I ++) {
// if the current first number to be calculated is greater than 0, after certain numbers which is greater than 0 (as it has been sorted), the sum of three numbers must be greater than 0, the end of the cycle
IF (the nums [I]> 0) {BREAK;}
// first number of the three numbers of deduplication
IF (I> 0 && the nums [I] == the nums [-I. 1]) {Continue;}
// second number index address
int L = I +. 1;
// address of the third number subscript
R = nums.length. 1-int;
// second number when the number of addresses in the third address R L when the front traversing all cases
while (L <R){
int sum = nums[i] + nums[L] + nums[R];
IF (SUM == 0) {
List.add (Arrays.asList (the nums [I], the nums [L], the nums [R & lt]));
// the three digits to a second number of weight
while (L <R & lt && the nums [L] == the nums [L +. 1]) {L ++;}
// third number three to the number of weight
while (L <R && nums [ R] == nums [R- . 1]) {R--;}
// case where the sum == 0, the first number remains the same, the second and the third number can not be repeated, so that the left traverse knitting continues rearwardly L , R continue to traverse the right forward
L ++;
R--;
}
// if <specifies the number num [L] to the left small sum 0, so the address + 1 to continue to traverse the left rearward
else if (sum <0 ) {L ++;}
// if sum> 0 described right number num [R] is too great, so to continue to traverse the right address -1 forward
the else iF (sum> 0) {R--;}
}
}
return List;
}

Guess you like

Origin www.cnblogs.com/cdlyy/p/12532208.html