题目概述
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
示例
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
基本思路
使用双指针法
先将数组排序,for循环取到两个数之后,再建立左指针,右指针。左指针靠近第二层for循环,右指针放在数组的尾端。(其实可以理解为四指针法,两个for循环也可以算作两个指针)。若sum小于target左指针右移,若sum大于target右指针左移,如此实现指针的动态性。
注:一旦找到符合要求的结果,则两个指针要同时内缩,否则陷入死循环!
代码实现
方法一
public List<List<Integer>> solution(int[] nums,int target){
//建立结果容器(因为要反复添加考虑到重复问题,故使用HashSet结构)
Set<List<Integer>> box = new HashSet<>();
//将数组排序
Arrays.sort(nums);
//建立左右指针
int left;
int right;
for(int i = 0;i < nums.length;i++){
for(int p = i + 1;p < nums.length;p++){
left = p + 1;
right = nums.length - 1;
while(left < right){
if(nums[i]+nums[p]+nums[left]+nums[right] < target){
left++;
}else if(nums[i]+nums[p]+nums[left]+nums[right] > target){
right--;
}else {
box.add(Arrays.asList(new Integer[]{nums[i],nums[p],nums[left],nums[right]}));
right--;
left++;
}
}
}
}
return new ArrayList<>(box);
}
方法二
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
left++;
right--;
}
}
}
}
return result;
}
总结
方法一比较粗糙,效率较低,而方法二加入了一些剪枝操作,更加高效快捷!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/122343.html