Leetcode 题目解析之 4Sum
【摘要】 Leetcode 题目解析之 4Sum
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)
public List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length < 4) {
return new ArrayList<List<Integer>>();
}
Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<List<Integer>>();
// 和3Sum一样,只是多了一个循环
for (int a = 0; a < nums.length - 3; a++) {
int target_3Sum = target - nums[a];
for (int b = a + 1; b < nums.length - 2; b++) {
int c = b + 1, d = nums.length - 1;
while (c < d) {
int sum = nums[b] + nums[c] + nums[d];
if (sum == target_3Sum) {
// 将结果加入集合
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[a]);
tmp.add(nums[b]);
tmp.add(nums[c]);
tmp.add(nums[d]);
set.add(tmp);
// 去重
while (++c < d && nums[c - 1] == nums[c])
;
while (--d > c && nums[d + 1] == nums[d])
;
}
else if (sum < target_3Sum) {
c++;
} else {
d--;
}
}
}
}
return new ArrayList<List<Integer>>(set);
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)