Leetcode 18 4Sum

来源:互联网 发布:喵咪看片软件最新版 编辑:程序博客网 时间:2024/04/17 07:17

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) 

Solution

  • 和3Sum类似,从固定第一个数开始,往下for循环层层嵌套,直到转化为2Sum问题,当然必须先排序。代码如下:
import java.util.*;public class Solution {    public List<List<Integer>> fourSum(int[] nums, int target) {        ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();        Arrays.sort(nums);        for(int i=0,a=Integer.MAX_VALUE;i<nums.length-3;i++){            if(nums[i]==a) continue;//跳过重复的数            a = nums[i];            for(int j=i+1,b=Integer.MAX_VALUE;j<nums.length-2;j++){                if(nums[j]==b) continue;                b = nums[j];                for(int p=j+1,q=nums.length-1,c=Integer.MAX_VALUE;p<q;){                    int temp = a+b+nums[p]+nums[q];                    if(nums[p]==c||temp<target) p++;                    else if(temp>target) q--;                    else{                        c = nums[p];//这个c和之前的a,b必须在已经找到一个解才能去更新,否则在当只有q--的时候,本来p指针应保持不变的也会跳过去了                        ArrayList<Integer> item = new ArrayList<Integer>();                        item.add(a);                        item.add(b);                        item.add(c);                        item.add(nums[q--]);                        p++;                        result.add(item);                    }                }            }        }        return result;            }}
  • 另外除了用一个数去保存前一个已考察过的数来去除重复这种方法之外,也可以用while循环判断上一个数是否和本次的数重复从而去重,详细见3Sum的Solution1.
  • 另外还有一种HashTable的方法是将数组两两相加,并将这些和连同相应两个数的下标一起存储到hashtable中,然后利用2Sum的方法来解决,但是这种思路有一个非常严重的问题就是去重相对麻烦。比如数组{1,2,3,4}, target=10,这个时候得到的HashTable是{3:(1,2), 4:(1,3), 5:{(1,4),(2,3)}, 6:(2,4), 7:(3,4)}。在这里至少有3+7与4+6这些组合等于10,但是最终答案只有一个就是1+2+3+4 = 10.所以利用HashTable可行,但是去重相对麻烦。感兴趣的可以参考HashTable解法。
0 0