首页 > 代码库 > 18. 4Sum
18. 4Sum
https://leetcode.com/problems/4sum/#/solutions
public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (num==null || num.length==0) return res;
Arrays.sort(num);
int max = num[num.length-1];
if (4 * num[0] > target || 4 * max < target)
return res;
for (int i=num.length-1; i>=3; i--) {
if (i<num.length-1 && num[i]==num[i+1]) continue;
threeSum(0, i-1, num, target-num[i], res, num[i]);
}
return res;
}
public void threeSum(int start, int end, int[] num, int target, List<List<Integer>> res, int last1) {
for (int i=end; i>=2; i--) {
if (i<end && num[i]==num[i+1]) continue;
twoSum(0, i-1, num, target-num[i], res, num[i], last1);
}
}
public void twoSum(int l, int r, int[] num, int target, List<List<Integer>> res, int last2, int last1) {
while (l < r) {
if (num[l]+num[r] == target) {
List<Integer> set = new ArrayList<Integer>();
set.add(num[l]);
set.add(num[r]);
set.add(last2);
set.add(last1);
res.add(new ArrayList<Integer>(set));
l++;
r--;
while (l<r && num[l] == num[l-1]) {
l++;
}
while (l<r && num[r] == num[r+1]) {
r--;
}
}
else if (num[l]+num[r] < target) {
l++;
}
else {
r--;
}
}
}
}
18. 4Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。