4Sum
来源:互联网 发布:c语言排序方法 编辑:程序博客网 时间:2024/05/19 18:11
Problem: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.
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)
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)
对于k-sum问题. 时间复杂度N^(k-1).
public static List<List<Integer>> fourSum(int[] nums, int target) {Arrays.sort(nums);ArrayList<List<Integer>> al=new ArrayList<List<Integer>>();HashSet<List<Integer>> hs=new HashSet<List<Integer>>();for(int i=0;i<nums.length;i++){for(int j=i+1;j<nums.length;j++){int start=j+1,end=nums.length-1;while(start<end){int sum=nums[i]+nums[j]+nums[start]+nums[end];if(sum<target)start++;else if(sum>target)end--;else{ArrayList<Integer> temp=new ArrayList<Integer>();temp.add(nums[i]);temp.add(nums[j]);temp.add(nums[start]);temp.add(nums[end]);if(!hs.contains(temp)){hs.add(temp);al.add(temp);}start++;end--;}}}}return al;}
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- ios开发动物园管理 继承多态的实现
- 教你透彻了解红黑树
- 网页中<li>分列显示
- FireEvent结合WSH实现右键菜单操作
- javascript 字符串加减法
- 4Sum
- 运行Maven时出现-Dmaven.multiModuleProjectDirectory system propery is not set.错误
- iOS 7从 NSURLConnection 到 NSURLSession
- hdu 1712, multiple-choice knapsack,
- 自定义spirng schema
- 小题一道~
- 移动web适配
- LINUX分区
- [LeetCode]Jump Game II(贪心&&DP!!!!!)