Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
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.
Example:
Given array nums = [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] ]
时间复杂度O(n3)
1 public List<List<Integer>> fourSum(int[] nums, int target) {//set my 2 List<List<Integer>> re = new ArrayList<>(); 3 //Set<List<Integer>> res = new HashSet<>(); 4 Arrays.sort(nums); 5 for (int i = 0; i < nums.length; i++) { 6 if(0<i&&nums[i]==nums[i-1]){ 7 continue; 8 } 9 for (int j = i+1; j < nums.length; j++) { 10 if((i+1)<j&&nums[j]==nums[j-1]){ 11 continue; 12 } 13 int k = j+1; 14 int l = nums.length-1; 15 while(k<l){ 16 if(target==(nums[i]+nums[j]+nums[k]+nums[l])){ 17 re.add(Arrays.asList(nums[i],nums[j],nums[k],nums[l])); 18 while(k<l&&nums[k]==nums[k+1])k++; 19 while(k<l && nums[l]==nums[l-1])l--; 20 k++; 21 l--; 22 } 23 else if(target>(nums[i]+nums[j]+nums[k]+nums[l])){ 24 k++; 25 } 26 else{ 27 l--; 28 } 29 } 30 } 31 } 32 return re; 33 }
该方法不是最优解
首先可以通过判断(可理解为剪枝)提高效率
是否存在低于O(n3)的方法?有待更新
相关题
两数之和 LeetCode1 https://www.cnblogs.com/zhacai/p/10429120.html
三数之和 LeetCode15 https://www.cnblogs.com/zhacai/p/10579514.html