15. 3Sum
题目描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
解题方法
變化馬甲: two sum == 0 - target
- 透過Sortu + Two
注意: skip duplicates
public List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> lists = new ArrayList<>();
if(nums == null || nums.length < 3){
return lists;
}
int n = nums.length;
Arrays.sort(nums);
for(int i = 0; i < n; i++){
if(i > 0 && nums[i - 1] == nums[i]){ //skip duplicates //****************************
continue;
}
//two pointer
int target = nums[i];
int left = i + 1;
int right = n - 1;
while(left < right){
List<Integer> list = new ArrayList<>();
if(nums[left] + nums[right] == 0 - target){
list.add(nums[left]);
list.add(nums[right]);
list.add(target);
lists.add(list);
left++;
right--;
while(left < right && nums[left] == nums[left - 1]){ //skip duplicates
left++;
}
while(left < right && nums[right] == nums[right + 1]){
right--;
}
}else if(nums[left] + nums[right] < 0 - target){
left++;
}else{
right--;
}
}
}
return lists;
}