leetcode的问题陈述说:
给定n个整数组成的数组S,S中是否存在元素a,b,c和d使得a + b + c + d =目标?在数组中找到所有给出目标总和的唯一四元组。
注意:
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.
关于这四个问题,我有两个问题:
import java.util.List; import java.util.ArrayList; import java.util.Collections; public class FourSumSolution{ public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target){ ArrayList<ArrayList<Integer>> aList = new ArrayList<ArrayList<Integer>>(); int N = num.length; for(int i=0; i<N; i++) for(int j=i+1; j<N; j++) for(int k=j+1; k<N; k++) for(int l=k+1; l<N; l++){ int sum = num[i] + num[j] + num[k] + num[l]; if(sum == target){ ArrayList<Integer> tempArray = new ArrayList<Integer>(); Collections.addAll(tempArray, num[i], num[j], num[k], num[l]); aList.add(tempArray); } } return aList; } }
这是一个O(n ^ 3)解决方案
import java.util.Arrays; import java.util.ArrayList; import java.util.HashSet; public class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { // Start typing your Java solution below // DO NOT write main() function Arrays.sort(num); HashSet<ArrayList<Integer>> hSet = new HashSet<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < num.length; i++) { for (int j = i + 1; j < num.length; j++) { for (int k = j + 1, l = num.length - 1; k < l;) { int sum = num[i] + num[j] + num[k] + num[l]; if (sum > target) { l--; } else if (sum < target) { k++; } else if (sum == target) { ArrayList<Integer> found = new ArrayList<Integer>(); found.add(num[i]); found.add(num[j]); found.add(num[k]); found.add(num[l]); if (!hSet.contains(found)) { hSet.add(found); result.add(found); } k++; l--; } } } } return result; }
}