
来源Leetcode第18题四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
这题思路其实和之前的三数之和是一样的,但是由于我自己逻辑不够完善,导致了卡在这题很久。
同样是采用双指针,先固定2个数,在对剩下2层进行遍历操作检查sum是否和target相等。
在最外层遍历时,受到了三数之和这题的影响,判断了第一层if nums[s] > target ,then break;
这其实是没有必要的,因为有负数的存在,当有负数时,连续几个负数相加会越来越小,从而满足target。
其次,在第二层遍历时,同样的,if nums[j] > target,then break;
这也是没必要的,原因同上。
最后附上完成代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
class { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList(); int len = nums.length; if(nums == null || len < 4) return ans; Arrays.sort(nums); for (int i = 0; i < len - 3; i++) { if(i > 0 && nums[i] == nums[i-1]) continue; if((nums[i] + nums[i+1] + nums[i+2] + nums[i+3])>target) break; if((nums[i]+nums[len-1]+nums[len-2]+nums[len-3])<target) continue; for(int j = i + 1;j<len - 2;j++) { if(j > i+1 && nums[j] == nums[j-1]) continue; if((nums[i] + nums[j] + nums[len - 1] + nums[len - 2]) < target) continue; if((nums[i] + nums[j] + nums[j+1] + nums[j+2])>target) break;
int L = j+1; int R = len-1; while(L < R){ int sum = nums[i] + nums[j] + nums[L] + nums[R]; if(sum == target){ ans.add(Arrays.asList(nums[i],nums[j],nums[L],nums[R])); while (L<R && nums[L] == nums[L+1]) L++; while (L<R && nums[R] == nums[R-1]) R--; L++; R--; } else if (sum < target) while(L<R&&nums[L]==nums[++L]); else if (sum > target) while(L<R&&nums[R]==nums[--R]); } } } return ans; } }
|
近期评论