4Sum
来源:互联网 发布:骑马动作数据 编辑:程序博客网 时间:2024/06/06 10:41
Q:
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)
Solution:
public class Solution { public List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (num.length < 4) return result; Arrays.sort(num); for (int i = 0; i < num.length; i++) { for (int j = i+1; j < num.length; j++) { int val = target - (num[i] + num[j]); List<Integer> list = new ArrayList<Integer>(); list.add(num[i]); list.add(num[j]); int p = j + 1; int q = num.length - 1; while (p < q) { if (num[p] + num[q] < val) p++; else if (num[p] + num[q] > val) q--; else { list.add(num[p]); list.add(num[q]); result.add(new ArrayList<Integer>(list)); list.remove(3); list.remove(2); p++; q--; while (p < q && num[p] == num[p-1]) p++; while (p < q && num[q] == num[q+1]) q--; } } while (j < num.length-1 && num[j] == num[j+1]) j++; } while (i < num.length-1 && num[i] == num[i+1]) i++; } return result; }}
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
- CUDA编程入门指南
- 设计模式之动态模式
- Spark vs. MapReduce 时间节约66%,计算节约40%
- dreamwrear cc 汉化
- 从拉普拉斯矩阵说到谱聚类
- 4Sum
- 从贝叶斯方法谈到贝叶斯网络
- Phoenix——实现向HBase发送标准SQL语句
- 关于面试Spring aop
- Foundation框架篇之NSNumber
- CSS的子选择器与后代选择器的区别
- StringBuffer
- CODE[VS] 1201
- 关于css中的block元素inline元素 以及positison属性的初步认识。