您的位置:首页 > 其它

4Sum

2015-10-08 21:15 260 查看
4Sum

定好左右两个游标,中间两个游标移动

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:

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)

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)


package com.rust.cal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum {

public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
int len = nums.length;
for (int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i-1])    continue;
for (int j = len - 1; j > i + 2; j--) {
if (j < len - 1 && nums[j] == nums[j+1])    continue;
int side = nums[i] + nums[j];
int left = i + 1;
int right = j - 1;
while (left < right) {
int inner = nums[left] + nums[right];
if (side + inner == target) {
List<Integer> singleAns = new ArrayList<Integer>();
singleAns.add(nums[i]);
singleAns.add(nums[left]);
singleAns.add(nums[right]);
singleAns.add(nums[j]);
res.add(singleAns);
while (left < right && nums[left] == nums[left+1]) left++;  //look forward
while (left < right && nums[right] == nums[right-1]) right--;   //skip the same number in nums[]
left++;
right--;
} else if (inner + side > target){
right--;
} else {
left++;
}
}
}
}
return res;
}

public static void main(String args[]){
List<List<Integer>> res = new ArrayList<List<Integer>>();
int[] nums = {-5,5,4,-3,0,0,4,-2};
int target = 4;
res = fourSum(nums, target);
/*output*/
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
System.out.println(res.size());
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res.get(i).size(); j++) {
System.out.print(res.get(i).get(j) + "\t");
}
System.out.println();
}
}

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