4Sum

来源:互联网 发布:骑马动作数据 编辑:程序博客网 时间:2024/06/06 10:41

Q:

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)

Solution:

public class Solution {    public List<List<Integer>> fourSum(int[] num, int target) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if (num.length < 4)            return result;        Arrays.sort(num);        for (int i = 0; i < num.length; i++) {            for (int j = i+1; j < num.length; j++) {                int val = target - (num[i] + num[j]);                List<Integer> list = new ArrayList<Integer>();                list.add(num[i]);                list.add(num[j]);                int p = j + 1;                int q = num.length - 1;                while (p < q) {                    if (num[p] + num[q] < val)                        p++;                    else if (num[p] + num[q] > val)                        q--;                    else {                        list.add(num[p]);                        list.add(num[q]);                        result.add(new ArrayList<Integer>(list));                        list.remove(3);                        list.remove(2);                        p++;                        q--;                        while (p < q && num[p] == num[p-1])                            p++;                        while (p < q && num[q] == num[q+1])                            q--;                    }                }                while (j < num.length-1 && num[j] == num[j+1])                    j++;            }            while (i < num.length-1 && num[i] == num[i+1])                i++;        }        return result;    }}


0 0
原创粉丝点击