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; } }
相关文章推荐
- LeetCode 18. 4Sum
- LeetCode 18 4Sum
- [LeetCode]--18. 4Sum
- LeetCode之18---4Sum
- leetcode 18 -- 4Sum
- 【C++】【LeetCode】15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- [LeetCode-Java]18. 4Sum
- Leetcode-18. 4Sum
- LeetCode 16. 3Sum Closest LeetCode 18. 4Sum
- LeetCode-18. 4Sum
- Leetcode[18]-4Sum
- leetcode 18. 4Sum
- LeetCode - 18. 4Sum
- LeetCode 18. 4Sum
- leetcode 18 4Sum
- [leetcode 18]4Sum
- Leetcode 18 : 4sum
- [leetcode]18. 4Sum
- LeetCode 18 4Sum
- LeetCode (18)4Sum