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. bootstrap-multiselect.js多选下拉框初始化时默认选中初始值

    bootstrap-multiselect.js多选下拉框默认值设置 一.案例数据格式  二.HTML代码 <select id="msgRoles" multiple=&q ...

  2. luogu4566 [Vani有约会]雨天的尾巴

    题目 线段树合并的板子题目了,写一写对线段树合并的理解 首先线段树合并就是把一大堆权值线段树合并起来的算法 尽管复杂度看起来并不是非常科学,但是确是非常优秀的\(O(nlogn)\) 主要的写法两种 ...

  3. EXCRT

    是个好东西,可以处理在模数不互质的同余方程组 核心就是用扩欧来合并方程 如果我们有两个形如\(x\equiv b_1(mod\ a_1)\) \(x\equiv b_2(mod\ a_2)\)的方程我 ...

  4. Spring+Velocity+Mybatis入门

    转自:https://blog.csdn.net/duqi_2009/article/details/47752169 一.开发工具 开发过程中使用的操作系统是OS X,关于软件安装的问题请大家移步高 ...

  5. WP | 后台PHP脚本无法修改及服务器无法直接写入问题的解决

    问题描述 试图修改页脚的时候,发现WordPress后台Appearance(外观)选项之下没有Editor(编辑)的子选项,之后进行设置修改后又发现无法保存. 试图安装插件,但是无法直接安装,推测是 ...

  6. iOS程序的启动原理

    一.在一些老的项目中,有很多不是通过代码添加窗口和跟控制器.是通过设置MainInterface(设置最主要的xib),在xib中通过图形化的操作设置应用程序的代理->设置窗口->设置根控 ...

  7. LINQ 方法

    过滤操作符 Where 运算符(Linq扩展方法)根据给定条件过滤集合. 在其中扩展方法有以下两个重载.一个过载需要Func <TSource,bool>输入参数和第二个重载方法需要Fun ...

  8. AngularJS web应用程序

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...

  9. 与JSON相关的问题

    1.JSON.stringify 与 JSON.parse 相关的问题 JSON.stringify 把字符串转化为字符串,JSON.parse把字符串转化为JSON格式 会出现的问题Unexpect ...

  10. Swift_控制流

    Swift_控制流 点击查看源码 for-in 循环 //for-in 循环 fileprivate func testForIn() { //直接循环提取内部数据 //[1,5] for index ...