[Leetcode] 4Sum
一、使用2sum降低复杂度为O(N^2)
1 public class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 Arrays.sort(nums); 4 List<List<Integer>> res = new LinkedList<List<Integer>>(); 5 for(int i=0;i<nums.length-3;i++){ 6 if(i!=0&&nums[i-1]==nums[i]) continue; 7 for(int j=i+1;j<nums.length-2;j++){ 8 if(j!=i+1&&nums[j-1]==nums[j]) continue; 9 int sum = target - (nums[i]+nums[j]); 10 int left = j+1; 11 int right = nums.length-1; 12 while(left<right){ 13 int tmpsum = nums[left] + nums[right]; 14 if(tmpsum==sum){ 15 List<Integer>listone = new LinkedList<Integer>(); 16 listone.add(nums[i]); 17 listone.add(nums[j]); 18 listone.add(nums[left]); 19 listone.add(nums[right]); 20 res.add(listone); 21 left++; 22 right--; 23 while(left<right&&nums[left-1]==nums[left]) left++; 24 while(left<right&&nums[right]==nums[right+1]) right--; 25 }else if(tmpsum < sum){ 26 left++; 27 while(left<right&&nums[left-1]==nums[left]) left++; 28 } 29 else{ 30 right--; 31 while(left<right&&nums[right]==nums[right+1]) right--; 32 } 33 } 34 } 35 } 36 return res; 37 } 38 }
二、和3Sum是一样的,只是多了一层循环而已。
1 public class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 Arrays.sort(nums); 4 List<List<Integer> > listall = new LinkedList<List<Integer> >(); 5 for(int i=0;i<nums.length;i++){ 6 int num1=nums[i]; 7 if(i>0&&num1==nums[i-1]) continue; 8 for(int j=i+1;j<nums.length;j++){ 9 int num2=nums[j]; 10 if(j>i+1&&num2==nums[j-1]) continue; 11 for(int k=j+1;k<nums.length;k++){ 12 int num3=nums[k]; 13 if(k>j+1&&num3==nums[k-1]) continue; 14 for(int m=k+1;m<nums.length;m++){ 15 int num4=nums[m]; 16 if(m>k+1&&num4==nums[m-1]) continue; 17 int sum=num1+num2+num3+num4; 18 if(sum==target){ 19 List<Integer> listone = new LinkedList<Integer>(); 20 listone.add(num1); 21 listone.add(num2); 22 listone.add(num3); 23 listone.add(num4); 24 listall.add(listone); 25 } 26 if(sum>target) 27 break; 28 } 29 } 30 } 31 } 32 return listall; 33 } 34 }