题目链接:https://leetcode-cn.com/problems/4sum/
题目介绍:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
解题思路:
- 先对数组进行排序,然后两个for循环确定两个值后,通过左右指针确定后面两个数
- 两个for循环在进行循环的时候需进行去重处理
- 判断两个for循环和左右指针相加的值和target的大小进行判断,移动左右指针,从而确定目标值
- 确定左右指针位置后,对左右指针分别进行判重处理
/**
* @author: hyl
* @date: 2019/08/03
**/
public class Que18 {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
if (nums.length < 4){
return resultList;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length-2; i++) {
//去重处理
if (i > 0 && nums[i] == nums[i-1]){
continue;
}
for (int j = i+1; j < nums.length-1; j++) {
//去重处理
if (j > i+1 && nums[j] == nums[j-1]){
continue;
}
//定义两个指针
int l = j + 1;
int r = nums.length-1;
while (l < r){
int sum = nums[i] + nums[j] + nums[l] + nums[r];
//分别移动两个指针
if (sum < target){
l++;
}else if (sum > target){
r--;
}else{
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[l]);
list.add(nums[r]);
resultList.add(list);
//进行去重
while (l < r-1 && nums[l] == nums[l+1]){
l++;
}
while (r < nums.length-1 && nums[r] == nums[r+1]){
r--;
}
l++;
r--;
}
}
}
}
return resultList;
}
}
总结:
- 通过两个for循环个两个指针可以把复杂度提升到O(N^2 * logN)
- 在进行for循环时需进行判重处理
- 在得到确定的左右指针后需要进行判重处理
代码地址:
https://github.com/Han-YLun/LeetCode/blob/master/Practice/src/Que18.java
文章为阿伦原创,如果文章有错的地方欢迎指正,大家互相交流。