leetcode(18)四数之和
四数之和
解题思路:排序+Hash+双指针
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { int len = nums.length; Arrays.sort(nums); Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<len;i++){ map.put(nums[i],i); } int l = 0; int r = 0; int temp = 0; int target2 = 0; List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> list = null; int count = 1; int root = 1; for(int i=0;i<len-3;i++){ if(i+1<len-3+root-1&&nums[i+1]==nums[i]){ root++; if(root==3){//这里求的是前三个或者前四个数相等的情况 target2 = target - 3*nums[i]; if(map.get(target2)!=null&&map.get(target2)>i+1){ list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[i]); list.add(nums[i]); list.add(target2); result.add(list); } } continue; } if(root>=2){//这里求的是前两个数相等的情况 l=i+1; r=len-1; target2 = target - 2*nums[i]; if(l<r&&nums[r-1]+nums[r]<target2&&nums[l]+nums[l+1]>target2){ }else{ while(l<r){ temp = nums[l]+nums[r]; if(temp>target2){ while(l<r&&nums[r-1]==nums[r]){ r--; } r--; }else if(temp<target2){ while(l<r&&nums[l+1]==nums[l]){ l++; } l++; }else{ list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[i]); list.add(nums[r]); list.add(nums[l]); result.add(list); while(l<r&&nums[r-1]==nums[r]){ r--; } r--; while(l<r&&nums[l+1]==nums[l]){ l++; } l++; } } } } root=1; count =1; for(int j=i+1;j<len-2;j++){ if(j+1<len-2+count-1&&nums[j+1]==nums[j]){ count++; if(count==2){//后三个数相等或者中间两个数相等的情况 target2 = target - nums[i] - 2*nums[j]; if(map.get(target2)!=null&&map.get(target2)>j+1){ list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[j]); list.add(target2); result.add(list); } } continue; } count=1; l = j+1; r = len-1; target2 = target - nums[i] - nums[j]; if(l<r&&nums[r-1]+nums[r]<target2&&nums[l]+nums[l+1]>target2){ }else{ while(l<r){//四个数都不相等或者后两个数相等的情况 temp = nums[l]+nums[r]; if(temp>target2){ while(l<r&&nums[r-1]==nums[r]){ r--; } r--; }else if(temp<target2){ while(l<r&&nums[l+1]==nums[l]){ l++; } l++; }else{ list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[r]); list.add(nums[l]); result.add(list); while(l<r&&nums[r-1]==nums[r]){ r--; } r--; while(l<r&&nums[l+1]==nums[l]){ l++; } l++; } } } } } return result; } }