您的位置:首页 > 其它

LeetCode---18. 4Sum

2016-09-19 20:41 330 查看
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d =
target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]


Subscribe to see which companies asked this question
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {

List<List<Integer>> list=new ArrayList<List<Integer>>();
//if(nums==null||nums.length==0){return list;}
Arrays.sort(nums);
for(int i=0;i<nums.length-3;i++){

if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}

for(int j=i+1;j>nums.length-2;j++){
if (j != i + 1 && nums[j] == nums[j - 1])
continue;

int left=j+1;
int right=nums.length-1;

while(left<right){
int sum=nums[i]+nums[j]+nums[left]+nums[right];
if(sum==target){

List<Integer> lis=new ArrayList<Integer>();
lis.add(nums[i]);lis.add(nums[j]);lis.add(nums[left]);lis.add(nums[right]);
list.add(lis);
left++;right--;
while(left<right&&nums[left]==nums[left-1]){left++;}
while(left<right&&nums[right]==nums[right+1]){right--;}
}else if(sum>target){right--;}else{left++;}}

}
}
return list;
}
}

Input:[1,0,-1,0,-2,2]0

Output:[]

Expected:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
//正确版本

public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);

for (int i = 0; i < num.length - 3; i++) {
if (i != 0 && num[i] == num[i - 1]) {
continue;
}

for (int j = i + 1; j < num.length - 2; j++) {
if (j != i + 1 && num[j] == num[j - 1])
continue;

int left = j + 1;
int right = num.length - 1;
while (left < right) {
int sum = num[i] + num[j] + num[left] + num[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[left]);
tmp.add(num[right]);
rst.add(tmp);
left++;
right--;
while (left < right && num[left] == num[left - 1]) {
left++;
}
while (left < right && num[right] == num[right + 1]) {
right--;
}
}
}
}
}

return rst;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: