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. 一点一点学写Makefile(4) - 编译时指定宏参数

    我们在项目中有时为了方便会自定义一些与项目无关的功能,例如打印输出一些提示信息.将关键协议生成文件等,但是如果每次都通过修改代码的方法来实现,测试部门就会认为你改的这些代码可能会带来其他问题.对于这种 ...

  2. SSD 从形式到实质之改变

    SSD 从形式到实质之改变  作者:廖恒          SSD的物理尺寸之混战正在进行其中. 数据中心的硬件架构师由于要规划下一代server的机械设计.还要制定JBOD的设计规范,想必面临不少困 ...

  3. 【Unity3D】【NGUI】UIRect的Anchor的使用

    NGUI版本号:3.6.5 以以下的图,解释下主要的Anchors的使用(能够通过官方的Anchor和Chat样例进行深入学习) Target不是一定要是Sprite.能够是随意的UIRect(UIS ...

  4. HDU 3613 扩展KMP

    暴力枚举大水题,判断回文,扩展KMP #include <cstdio> #include <cstring> #include <algorithm> using ...

  5. Nodejs做整站转发

    刚接触nodejs,做个东西练下手,通过nodejs直接转发整站,原本想把内容全翻译成英文,但google对流量行审查,被封IP,所以就没啥用了, 效果像这样 var b = function (a, ...

  6. java基础(杂记)

    java基础夯实(杂记):1:创建实例对象可以通过无参的构造函数然后调用成员变量去初始化属性,也可以自己定义有参构造方法直接初始化属性,当属性为private时我们可以通过getset方法间接访问:2 ...

  7. js,h5页面判断客户端是ios还是安卓

    $(function(){ var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('An ...

  8. js关于密码框强弱度的提示

    三种密码强度的正则表达式: 较弱:全是数字或全是字母 6-16个字符:/^[0-9]{6,16}$|^[a-zA-Z]{6,16}$/; 中级:数字.26个英文字母 6-16个字符: /^[A-Za- ...

  9. jsp+spring+jquery+ajax的简单例子

    初学b/s编程,花费了许多时间,进度颇慢! 不过终于完成了一个简单的例子: jsp代码 <%@ page language="java" contentType=" ...

  10. 详解Linux运维工程师

    运维工程师是从一个呆逼进化为苦逼再成长为牛逼的过程,前提在于你要能忍能干能拼,还要具有敏锐的嗅觉感知前方潮流变化.如:今年大数据,人工智能比较火……(相对表示就是 Python 比较火) 之前写过运维 ...