题目描述:
给定阵列小号的Ñ整数,是否有元件一个,a, b, c, 和 d在小号使得一个 a + b + c + d = target 找到数组中给出目标总和的所有唯一四元组。
注意:解决方案集不能包含重复的四元组。
结果分析:
输入:given array S = [1, 0, -1, 0, -2, 2], and target = 0.
输出:[ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]代码如下:public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list=new ArrayList<>(); if(nums.length<4) return list; Arrays.sort(nums);//进行了排序 for(int i=0;i<nums.length-3;i++) { if(i>0&&nums[i]==nums[i-1]) continue; for(int j=i+1;j<nums.length-2;j++) { if(j>i+1&&nums[j]==nums[j-1]) continue; int start=j+1,end=nums.length-1; while(start<end) { int sum=nums[i]+nums[j]+nums[start]+nums[end]; if(sum==target) { list.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end])); while(start<end&&nums[start]==nums[start+1]) start++; while(start<end&&nums[end]==nums[end-1]) end--; start++; end--; } else if(sum>target) end--; else start++; } } } return list; }
662

被折叠的 条评论
为什么被折叠?



