[Leetocde] 4Sum (Java)

来源:互联网 发布:python搭建webservice 编辑:程序博客网 时间:2024/06/06 14:17

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)

比3sum多了一层循环O(n3),没想到更简单的办法

public class Solution {    public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();Arrays.sort(num);for(int i=0;i<num.length-3;i++){for(int j=i+1;j<num.length-2;j++) {int a = num[i];int b = num[j];int start = j+1;int end = num.length-1;while(start<end){int c = num[start];int d = num[end];if(a+b+c+d==target){ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(a);temp.add(b);temp.add(c);temp.add(d);set.add(temp);start++;end--;}else if(a+b+c+d<target){start++;}else {end--;}}}}res.addAll(set);return res;           }}


0 0
原创粉丝点击