4Sum
来源:互联网 发布:唯一视觉婚纱摄影 知乎 编辑:程序博客网 时间:2024/06/18 17:31
原题:
Given an array S of n integers, are there elements a,b, c, and d in S such that a + b +c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.A solution set is:[ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2]]
即从给定数组找出和为target的所有情况且不能重复。
思考过程&解题思路:
依旧是双指针算法,在3Sum上嵌套一层循环。
结果代码:
public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList<>(); for (int i = 0;i < nums.length;i++){ if ((i > 0) && (nums[i] == nums[i - 1])) continue; for (int j = i + 1;j < nums.length - 2;j++){ if ((j > i + 1) && (nums[j] == nums[j - 1])) continue; int l = j + 1,r = nums.length - 1; while (l < r){ if ((l > j + 1) && (nums[l] == nums[l - 1])) { l++;continue; } if ((r < nums.length - 1) && (nums[r] == nums[r + 1])) { r--;continue; } int sum = nums[l] + nums[r] + nums[i] + nums[j]; if (sum > target) r--; if (sum < target) l++; if (sum == target){ List<Integer> integers = new ArrayList<>(); integers.add(nums[i]); integers.add(nums[j]); integers.add(nums[l]); integers.add(nums[r]); res.add(integers); r--;l++; } } } }return res;}
阅读全文
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- java知识点
- 20170919--安装mysql遇到的问题
- Java记录
- elasticsearch笔记(1)
- 为完成的JAVA 学生与课程类
- 4Sum
- c++编程题2
- selenium之开发登录脚本_maven版本一
- hdu--4884--TIANKENG’s rice shop【模拟】
- HDU 2428
- 彻底解决QT编码问题
- 【and or分块】51Nod1674[区间的价值 V2]题解
- 由JDBC事务引起的锁状态以及内存数据无法写入数据库的问题
- Unknown feature (Run Configuration[AndroidRunConfigurationType]) covered by disabled plugin detecte