4Sum

来源:互联网 发布:linux软件下载 编辑:程序博客网 时间:2024/06/17 15:19

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: 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]]

求4个数的和,其实可以像求三个数的和那样,先固定一个数,然后接下来就可以简化为求三个数的和了。

public class Solution {    public List<List<Integer>> fourSum(int[] nums, int target) {        Arrays.sort(nums);List<List<Integer>> res = new ArrayList<List<Integer>>();if (nums == null || nums.length<4) {return res;}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++) {//在上一个以固定的数的基础上再固定一个数,接下来可以简化为求3 Sumif (j > i+1&& nums[j]==nums[j-1]) continue; int begin = j+1;int end = nums.length-1;while (begin < end) {int sum = nums[i] + nums[j] + nums[begin] + nums[end];if (sum == target) {List<Integer> list = new ArrayList<Integer>();list.add(nums[i]);list.add(nums[j]);list.add(nums[begin]);list.add(nums[end]);res.add(list);//存入到结果集中//下面的两个while,可以避免结果集中有重复,因为数组是排好序的,//所以当一个数被放到结果集中的时候,其后面和它相等的直接被跳过。//右移的时候如果相等就继续右移while (begin < end && nums[begin] == nums[begin+1]) {begin++;}//左移的时候如果相等就继续左移while (begin < end && nums[end] == nums[end-1]) {end--;}begin++;end--;}else if (sum < target) {begin++;}else {//sum>targetend--;}}}}return res;}    }
查了下资料有用hash算法的,但是我现在的知识水平还不太会。过阵子再研究优化一下。

0 0
原创粉丝点击