/**
* 先排序数组.从小开始遍历数组求:-arr[i]=arr[x] + arr[y],y>x>i
* 问题变成2Sum
* Created by lezg on 16/4/5.
*/
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length < 3) {
return res;
}
Arrays.sort(nums);
if (nums[0] > 0) {
return res;
}
int len = nums.length - 2;
for (int i = 0; i < len; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
find(nums, i + 1, len + 1, nums[i]);
}
return res;
}
public void find(int[] nums, int start, int end, int target) {
while (start < end) {
if (nums[start] + nums[end] + target == 0) {
List<Integer> ts = new ArrayList<>();
ts.add(target);
ts.add(nums[start]);
ts.add(nums[end]);
res.add(ts);
while (start < end && nums[start] == nums[start + 1]) {
++start;
}
while (start < end && nums[end] == nums[end -1]) {
--end;
}
++start;
--end;
}else if (nums[start] + nums[end] + target < 0) {
++start;
}else {
--end;
}
}
}
}