LeetCode : 4Sum [java]
来源:互联网 发布:2016年最红的网络歌曲 编辑:程序博客网 时间:2024/04/30 08:15
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
思路:确定前两个,双指针扫描后两个。
import java.util.Arrays;import java.util.List;import java.util.ArrayList;public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) {List<List<Integer>> list = new ArrayList<List<Integer>>();if (nums == null || nums.length < 4) {return list;}Arrays.sort(nums);for (int i = 0; i < nums.length; i++) {while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) {i++;}for (int j = i + 1; j < nums.length; j++) {while (j > i + 1 && j < nums.length && nums[j] == nums[j - 1]) {j++;}int left = j + 1;int right = nums.length - 1;while (left < right) {int sum = nums[i] + nums[j] + nums[left] + nums[right];if (sum > target) {while (right > left && nums[right] == nums[right - 1]) {right--;}right--;} else if (sum < target) {while (left < right && nums[left] == nums[left + 1]) {left++;}left++;} else {List<Integer> interList = new ArrayList<Integer>();interList.add(nums[i]);interList.add(nums[j]);interList.add(nums[left]);interList.add(nums[right]);list.add(interList);while (left < right && nums[left] == nums[left + 1]) {left++;}left++;}}}}return list; }}
1 0
- 4Sum leetCode Java
- [LeetCode][Java] 4Sum
- LeetCode : 4Sum [java]
- leetcode 4Sum(Java)
- 4 Sum leetcode java
- LeetCode – 4Sum (Java)
- [leetcode-18]4Sum(java)
- (Java)LeetCode-18. 4Sum
- leetcode-Java-18. 4Sum
- [LeetCode-Java]18. 4Sum
- [LeetCode] 18. 4Sum java
- 【Leetcode】4Sum (Sum)
- LeetCode – 4Sum (Java)题解
- Leetcode 18. 4Sum (Medium) (java)
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] Combination Sum (Java)
- [Leetcode] 3Sum (Java)
- 欢迎使用CSDN-markdown编辑器
- 科维PLC运行时系统ProConOS embedded CLR 2.2 特定应用
- JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
- [转载]微服务实战(二):使用API Gateway
- NetworkManager asks for password every time when i try to connect
- LeetCode : 4Sum [java]
- HTML5 data-* 自定义属性
- onclientclick和onclick区别
- Android加载webview 弹出错误
- uboot基本命令详解
- 【ShawnZhang】带你看蓝桥杯——算法训练Torry的困惑(基本型)
- MFS的MASTER启动出现错误
- 杂货铺
- oracle insert into 多个value