[LeetCode] 4Sum
2014-04-23 15:03
330 查看
Question : 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.
思路:
Note : 这个跟3sum也挺像。 定义一对指针,指向两头。再定义一对指针,指向中间的两个元素。加起来看看跟target比较一下。决定内部指针怎么移动。
用到了Arrays.sort() 方法,该方法是一种改进的快排,时间复杂度最优情况 O(N*logN)
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)
思路:
Note : 这个跟3sum也挺像。 定义一对指针,指向两头。再定义一对指针,指向中间的两个元素。加起来看看跟target比较一下。决定内部指针怎么移动。
用到了Arrays.sort() 方法,该方法是一种改进的快排,时间复杂度最优情况 O(N*logN)
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public class FourSum { public ArrayList fourSum (int[] num, int target) { HashSet rs = new HashSet(); int len = num.length; Arrays.sort(num); if(len <= 3) return new ArrayList(rs); for(int i = 0; i < len-3; i++) { for(int k = len-1; k > i+2; k--) { int ab = num[i] + num[k]; int c = target-ab; int m = i+1; int n = k-1; while(m < n) { int sum = num[m] + num ; if(sum == c) { ArrayList elem = new ArrayList(); elem.add(num[i]); elem.add(num[m]); elem.add(num ); elem.add(num[k]); rs.add(elem); m++; n--; } else if(sum < c) { m++; } else n--; } } } return new ArrayList(rs); } }
相关文章推荐
- LeetCode 18 4Sum
- LeetCode - 18. 4Sum
- LeetCode -- 4Sum
- 4Sum——LeetCode
- 【Leetcode】之4Sum
- LeetCode--4sum
- [LeetCode18]4Sum
- C实现 LeetCode->4Sum
- 4Sum_leetCode
- leetcode 18. 4Sum
- 第五周:[leetcode] Two Sum、3Sum、3Sum Closest、4Sum
- Java [leetcode 18]4Sum
- leetcode-18. 4Sum
- 4Sum_Leetcode_#18
- [LeetCode]4Sum
- leetcode 3sum closest && 4sum
- LeetCode 4Sum
- [LeetCode]4Sum
- [LeetCode] 4Sum
- LeetCode18:4Sum