您的位置:首页 > 其它

Leetcode 18. 4Sum

2017-01-02 11:26 495 查看
public class Solution {
// two-pointer to search three numbers sum to target
public static void threeSum(List<List<Integer>> res, int start, int goal, int target, int[] nums) {
for (int i=start; i<nums.length-2; i++) {
// skip some duplicates
if (i==start || nums[i] != nums[i-1]) {
int low = i+1, high = nums.length-1, sum = goal-nums[i];
while (low < high) {
if (sum == nums[low]+nums[high]) {
res.add(new ArrayList<>(Arrays.asList(target-goal, nums[i], nums[low], nums[high])));
// skip some duplicates
while (low < high && nums[low] == nums[low+1]) low++;
while (low < high && nums[high] == nums[high-1]) high--;
low++; high--;
}
else if (sum > nums[low]+nums[high])
low++;
else
high--;
}
}
}
}

public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int start = 0, goal = 0;
List<List<Integer>> res = new ArrayList<>();
for (int i=0; i<nums.length-3; i++) {
if (i==0 || nums[i] != nums[i-1]) {
goal = target - nums[i];
start = i + 1;
threeSum(res, start, goal, target, nums);
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: