18. 4Sum

来源:互联网 发布:wordpress 速度优化 编辑:程序博客网 时间:2024/05/22 10:27

Given an array S of n integers, are there elements abc, 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)

思路:和2sum一样的思路

代码如下(已通过leetcode)

public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(nums==null||nums.length<=3) return lists;
int n = nums.length;
Arrays.sort(nums);
for (int i = 0; i <= n - 4; i++) {


for (int j = i + 1; j <= n - 3; j++) {


int start = j + 1;
int end = n - 1;
while (start < end) {
if ((nums[i] + nums[j] + nums[start] + nums[end]) == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[start]);
list.add(nums[end]);
if(!lists.contains(list)) lists.add(list);
start++;
end--;
} else {
if ((nums[i] + nums[j] + nums[start] + nums[end]) > target)
end--;
else
start++;
}
}


}
}
return lists;
}
}

0 0
原创粉丝点击