public List<List<Integer>> threeSum(int[] nums) {
return threeSumTarget(nums,0);
}
public List<List<Integer>> threeSumTarget(int []nums,int target){
Arrays.sort(nums);
int len = nums.length;
List<List<Integer>> result = new LinkedList<>();
for(int i = 0;i < len; i++){
//对target - nums[i] 计算twoSum
List<List<Integer>> tuples = twoSumTarget(nums,i + 1,target - nums[i]);
for(List<Integer> tuple : tuples){
tuple.add(nums[i]);
result.add(tuple);
}
while(i < len - 1 && nums[i] == nums[i+1])
i++;
}
return result;
}
public List<List<Integer>> twoSumTarget(int []nums,int start,int target){
int low = start,high = nums.length - 1;
List<List<Integer>> res = new LinkedList<>();
while(low < high){
int sum = nums[low] + nums[high];
int left = nums[low],right = nums[high];
if(sum < target){
while(low < high && nums[low] == left)
low++;
}else if(sum > target){
while(low < high && nums[high] == right)
high--;
}else{
List<Integer> temp = new LinkedList<>();
temp.add(left);
temp.add(right);
res.add(temp);
while(low < high && left == nums[low])
low++;
while(low < high && right == nums[high])
high--;
}
}
return res;
}
三数之和总结
最新推荐文章于 2022-04-10 14:57:24 发布