Piggy Bank of Cooooooode
阿新 • • 發佈:2018-12-21
Extend from 3Sum. Add another for loop. Slow Version
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4)
return res;
int len = nums.length;
Arrays.sort(nums);
for(int i=0;i<len-3;i++){
if(i>0 && nums[i]==nums[i-1]){
continue;
}
for(int j=i+1;j<len-2;j++){
if(j>i+1 && nums[j]==nums[j-1]){
continue;
}
int left=j+1;
int right=len-1;
while(left<right){
int sum=nums[i]+nums[j]+nums[left]+nums[right];
if(sum==target){
res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
while (left<right && nums[left]==nums[left+1]){left++;}
while(left<right && nums[right]==nums[right-1]){right--;}
left++;
right--;
}
else if(sum<target){
left++;
}
else{
right--;
}
}
}
}
return res;
}
}
Fast Version
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4)
return res;
int len = nums.length;
Arrays.sort(nums);
for(int i=0;i<len-3;i++){
if(i>0 && nums[i]==nums[i-1]){continue;}
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target){continue;}//add
if(nums[i]+nums[len-3]+nums[len-2]+nums[len-1]<target){continue;}//add
for(int j=i+1;j<len-2;j++){
if(j>i+1 && nums[j]==nums[j-1]){continue;}
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target){continue;}//add
if(nums[i]+nums[j]+nums[len-1]+nums[len-2]<target){continue;}//add
int left=j+1;
int right=len-1;
while(left<right){
int sum=nums[i]+nums[j]+nums[left]+nums[right];
if(sum==target){
res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
while(left<right && nums[left]==nums[left+1]){left++;}
while(left<right && nums[right]==nums[right-1]){right--;}
left++;
right--;
}
else if(sum<target){
left++;
}
else{
right--;
}
}
}
}
return res;
}
}