[Leetcode] 18. 4Sum
2015-03-12 22:30
295 查看
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.
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)
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(num.length < 4) return result; Arrays.sort(num); for(int i = 0; i < num.length - 3; i++){ if(i == 0 || num[i] != num[i - 1]){ for(int j = i + 1; j < num.length - 2; j++){ if(j == i + 1 || num[j] != num[j - 1]){ int start = j + 1; int end = num.length - 1; while(start < end){ if(num[i] + num[j] + num[start] + num[end] == target){ ArrayList<Integer> set = new ArrayList<Integer>(); set.add(num[i]); set.add(num[j]); set.add(num[start]); set.add(num[end]); result.add(set); start++; end--; while(start < end && num[start] == num[start - 1]){ start++; } while(start < end && num[end] == num[end + 1]){ end--; } } else if(num[i] + num[j] + num[start] + num[end] < target){ start++; } else { end-- ; } } } } } } return result; } }
相关文章推荐
- [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
- LeetCode_OJ【18】4Sum
- LeetCode 18_4Sum
- leetcode 18. 4Sum
- [leetcode] 18. 4Sum
- LeetCode (18)4Sum
- LeetCode 18. 4Sum
- leetcode question 18: 4Sum
- 【C语言】LeetCode 18 4Sum