18. 4Sum
来源:互联网 发布:wordpress 速度优化 编辑:程序博客网 时间:2024/05/22 10:27
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)
思路:和2sum一样的思路
代码如下(已通过leetcode)
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(nums==null||nums.length<=3) return lists;
int n = nums.length;
Arrays.sort(nums);
for (int i = 0; i <= n - 4; i++) {
for (int j = i + 1; j <= n - 3; j++) {
int start = j + 1;
int end = n - 1;
while (start < end) {
if ((nums[i] + nums[j] + nums[start] + nums[end]) == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[start]);
list.add(nums[end]);
if(!lists.contains(list)) lists.add(list);
start++;
end--;
} else {
if ((nums[i] + nums[j] + nums[start] + nums[end]) > target)
end--;
else
start++;
}
}
}
}
return lists;
}
}
- 15. 3Sum 和 18. 4Sum
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum LeetCode
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- Leetcode no. 213
- 【English】Enjoy your April
- [BZOJ1087][SCOI2005]互不侵犯King(状压dp)
- hadoop学习序曲之mysql基础篇--mysql基础
- VS2013 opencv2.4.9 配置过程若干问题
- 18. 4Sum
- 代码随想
- 编写安全的C代码
- sdau-2 1017
- 智力题
- Android chromium 和 Android Webkit 区别
- css3新增的文本高级样式-文本阴影和文本溢出
- Leetcode no. 337
- list.sort()