标签:
/* * 18. 4Sum * 2016-4-15 by Mingyang * 这个题目跟3sum一样的去重方法,不用HashSet,因为太慢,注意这个题目是4个的和为target,不为0 * 然后这里把判重条件改了一下,改为了 if(i>0&&nums[i]==nums[i-1]) continue; * 这么更言简意赅,同理,if(j>i+1&&nums[j]==nums[j-1])也是跳过 */ public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res=new ArrayList<List<Integer>>(); int len=nums.length; if(len<4) return res; Arrays.sort(nums); for(int i=0;i<len-3;i++){ if(i>0&&nums[i]==nums[i-1]) continue; for(int j=i+1;j<len-2;j++){ if(j>i+1&&nums[j]==nums[j-1]) continue; int start=j+1; int end=len-1; while(start<end){ int temp=nums[start]+nums[end]+nums[i]+nums[j]; if(temp==target){ List<Integer> list=new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[start]); list.add(nums[end]); res.add(list); while(start<end&&nums[start]==nums[start+1]) start++; while(start<end&&nums[end]==nums[end-1]) end--; start++; end--; }else if(temp<target){ start++; }else{ end--; } } } } return res; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5397980.html