1. 原题链接

https://leetcode.com/problems/4sum/description/

2. 题目要求

给出整数数组S[n],在数组S中是否存在a,b,c,d四个整数,使得四个数之和等于目标整数target。请找出所有满足此条件的四个整数。

3. 解题思路

先对nums进行排序,然后采用两层for循环来确定前两个数字,最后在第二层for循环中确定后两个数字。

注意可能存在重复解!!

如下图所示,对Input先进行排序:[-4, -1, -1,0, 1,2],target = -1

存在两个“-1”,因此要考虑结果去重。

使用 if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) 来对第一层for循环,即第一个数字去重。

如果对第二层for循环采用同样的方法去重,很可能导致丢失一个解,返回下图的错误结果。

[-4, -1, -1,0, 1,2],绿色表示第一层for循环遍历到的位置,红色表示第二层for循环开始的位置。如果使用 if (nums[j] != nums[j-1]) 来去重,就会跳过“-1”。

因此引入一个计数器count,来判断第二层for循环执行的次数。当count==1,即第二层for循环刚开始一次时,避免“-1”和“-1”的重复误判。

4. 代码实现

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class FourSum18 { public static void main(String[] args) {
int[] nums = {-1,-3,-2,2,3,-3,0,-4};
int target = 4;
List<List<Integer>> res = FourSum18.fourSum(nums, target);
for (List list : res) {
System.out.println(list);
}
} public static List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums); // 对nums进行排序 for (int i = 0; i < nums.length - 3; i++) {
int sum1 = target - nums[i];
if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { // 去除遍历第一个数字时重复的结果
int count =0;
for (int j = i + 1; j < nums.length - 2; j++) {
/**
* 需要判断遍历第二个数字存在重复解的可能
* 要同时考虑第一次遍历的位置
* 用count计数第二个数遍历的次数
*/
count++; if (nums[j] != nums[j-1]|| count==1) { // 去除遍历第二个数字时重复的结果
int sum2 = sum1 - nums[j], l = j + 1, r = nums.length - 1;
while (l < r) {
if (nums[l] + nums[r] == sum2) {
res.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 (sum2 < nums[l] + nums[r]) {
while (l < r && nums[r] == nums[r - 1]) r--;
r--; } else {
while (l < r && nums[l] == nums[l + 1]) l++;
l++;
}
}
}
} }
}
return res;
}
}

  

LeetCode:18. 4Sum(Medium)的更多相关文章

  1. LeetCode:11. ContainerWithWater(Medium)

    原题链接:https://leetcode.com/problems/container-with-most-water/description/ 题目要求:给定n个非负整数a1,a2,...,an  ...

  2. LeetCode:15. 3Sum(Medium)

    1. 原题链接 https://leetcode.com/problems/3sum/description/ 2. 题目要求 数组S = nums[n]包含n个整数,请问S中是否存在a,b,c三个整 ...

  3. LeetCode:46. Permutations(Medium)

    1. 原题链接 https://leetcode.com/problems/permutations/description/ 2. 题目要求 给定一个整型数组nums,数组中的数字互不相同,返回该数 ...

  4. LeetCode: 60. Permutation Sequence(Medium)

    1. 原题链接 https://leetcode.com/problems/permutation-sequence/description/ 2. 题目要求 给出整数 n和 k ,k代表从1到n的整 ...

  5. LeetCode: 61. Rotate List(Medium)

    1. 原题链接 https://leetcode.com/problems/rotate-list/description/ 2. 题目要求 给出一个链表的第一个结点head和正整数k,然后将从右侧开 ...

  6. LeetCode: 62. Unique Paths(Medium)

    1. 原题链接 https://leetcode.com/problems/unique-paths/description/ 2. 题目要求 给定一个m*n的棋盘,从左上角的格子开始移动,每次只能向 ...

  7. LeetCode: 56. Merge Intervals(Medium)

    1. 原题链接 https://leetcode.com/problems/merge-intervals/description/ 2. 题目要求 给定一个Interval对象集合,然后对重叠的区域 ...

  8. LeetCode: 55. Jump Game(Medium)

    1. 原题链接 https://leetcode.com/problems/jump-game/description/ 2. 题目要求 给定一个整型数组,数组中没有负数.从第一个元素开始,每个元素的 ...

  9. LeetCode: 54. Spiral Matrix(Medium)

    1. 原题链接 https://leetcode.com/problems/spiral-matrix/description/ 2. 题目要求 给定一个二维整型数组,返回其螺旋顺序列表,例如: 最后 ...

随机推荐

  1. MySQL学习(一) 数据表基本操作

    创建数据库:create database db_name 查看数据库结构:show create database db_name 删除数据库:drop database db_name 查看数据库 ...

  2. POJ-2976 Dropping tests---二分最大化平均值

    题目链接: https://cn.vjudge.net/problem/POJ-2976 题目大意: 给定n个二元组(a,b),扔掉k个二元组,使得剩下的a元素之和与b元素之和的比率最大 解题思路: ...

  3. POSIX 线程详解(经典必看)

    http://www.cnblogs.com/sunminmin/p/4479952.html 总共三部分: 第一部分:POSIX 线程详解                               ...

  4. 从零开始Vue项目实战(一)-准备篇

    从前参与过一个react项目的代码编写,大神搭建的框架,我主要负责业务逻辑代码编写,现在回想起来似乎又什么都不会,现在为了巩固前端知识,决定用Vue来做这个项目的移动端网站,我本人Vue是从零开始的, ...

  5. 2016 ACM/ICPC亚洲区大连站-重现赛 解题报告

    任意门:http://acm.hdu.edu.cn/showproblem.php?pid=5979 按AC顺序: I - Convex Time limit    1000 ms Memory li ...

  6. 2018.10.8 Hibernate中解决乱码问题---配置一个过滤器

    在web.xml中配置下 <filter> <filter-name>encodeFilter</filter-name> <filter-class> ...

  7. 【转】不错的linux下通用的java程序启动脚本

    虽然写起动shell的频率非常不高...但是每次要写都要对付一大堆的jar文件路径,新加jar包也必须要修改起动shell. 在网上找到一个挺好的通用shell脚本. 只需要修改一些配置变量,就可以用 ...

  8. Java中获取classpath路径下的资源文件

    ClassLoader 提供了两个方法用于从装载的类路径中取得资源: public URL  getResource (String name); public InputStream  getRes ...

  9. 用selenium爬动态网页

    0-安装 我用python2.7,用pip安装selenium即可,phantomjs到官网下载安装,也不难. 1-主要参考的几篇文章 Python爬虫利器四之PhantomJS的用法 Python爬 ...

  10. 【luogu P1195 口袋的天空】 题解

    题目链接:https://www.luogu.org/problemnew/show/P1195 嗯~我是被题目背景吸引到才做的,想吃棉花糖啦! 话说回来,这道题其实很容易就能想明白,k棵最小生成树. ...