LeetCode-18.4Sum
来源:互联网 发布:增加人脉的软件 编辑:程序博客网 时间:2024/04/30 01:19
https://leetcode.com/problems/4sum/
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: 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]]
方法1
利用题15.3Sum 的函数稍作修改,然后在外层再嵌套一层循环
public class Solution { public IList<IList<int>> FourSum(int[] nums, int target) { IList<IList<int>> res = new List<IList<int>>(); int n = nums.Length; if (n < 4) return res; Array.Sort(nums); for (int i = 0; i < n-3; i++) { var res3 = ThreeSum(i + 1, nums, target - nums[i]); if (res3.Count > 0) { foreach (var list in res3) { list.Insert(0, nums[i]); res.Add(list); } } while (i < n - 3 && nums[i] == nums[i + 1]) i++; } return res; } public IList<IList<int>> ThreeSum(int start,int[] nums,int target) { IList<IList<int>> res = new List<IList<int>>(); int n = nums.Length; int target2,l,r; for (int i = start; i < n-2; i++) { target2 = target - nums[i]; l = i + 1; r = n - 1; while (l<r) { if (nums[l] + nums[r] > target2) r--; else if (nums[l] + nums[r] < target2) l++; else { res.Add(new List<int>() { nums[i], nums[l] ,nums[r] }); while (i < n - 2 && nums[i] == nums[i + 1]) i++; while (l < n - 1 && nums[l] == nums[++l]); while (r > i + 1 && nums[r] == nums[--r]); } } } return res; }}
方法2
方法略繁琐,可以扩展到k-sum。有兴趣可以参考 http://blog.csdn.net/linhuanmars/article/details/24826871
0 0
- [LeetCode]18.4Sum
- LeetCode 18.4Sum
- leetcode 18.4Sum
- LeetCode-18.4Sum
- [LeetCode]18.4Sum
- [leetcode: Python]18.4Sum
- 【leetcode】18.4sum 总结
- LeetCode----- 18.4Sum
- Leetcode 18.4Sum
- 菜鸟刷leetcode 18.4Sum
- Leetcode——18.4Sum
- [leetcode]18.4Sum(Java实现)
- 【Leetcode】Path Sum (Sum)
- 【Leetcode】Two Sum (Sum)
- 【Leetcode】3Sum (Sum)
- 【Leetcode】4Sum (Sum)
- LeetCode 15.3Sum 18.4Sum 对撞指针 ****
- leetcode:leetcode :Path Sum
- Linux内核中的调度算法
- C基础中的知识点
- 创建一台拉倒服务器
- 204. Count Primes
- "快速排序"算法-之通俗易懂全面解析
- LeetCode-18.4Sum
- 判断二叉树是不是平衡树
- 关于iOS开发中颜色取色问题
- SpringMVC中文乱码 controller乱码
- 【整理】getopt和getopt_long函数
- 【Get深一度】信号处理(三)——3db带宽
- leetcode 114. Flatten Binary Tree to Linked List-二叉树变链表|指针
- 深入理解java虚拟机读书笔记-3.6内存分配与回收策略
- 01-java中“接口”的概念