LeetCode -- 4Sum
来源:互联网 发布:淘宝最低折扣0.7是什么 编辑:程序博客网 时间:2024/06/06 01:45
题目描述:
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)
(-2, 0, 0, 2)
在数组中找到四个数和=target。
和3Sum思路一模一样,就是外面多加了一层循环。
实现代码:
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)
(-2, 0, 0, 2)
在数组中找到四个数和=target。
和3Sum思路一模一样,就是外面多加了一层循环。
实现代码:
public class Solution { public IList<IList<int>> FourSum(int[] nums, int target) { if(nums == null || nums.Length < 4){ return new List<IList<int>>(); } var dic = new Dictionary<string, List<int>>(); var list = nums.OrderBy(x=>x).ToList(); var len = list.Count; for(var j = 0;j < len ; j++) { var d = list[j]; for (var i = 0 ;i <= len - 3 ;i++) { var a = list[i]; var start = i+1; var end = len-1; if(i == j){ continue; } while (start < end) { if(start == j){ start ++; continue; } if(end == j){ end --; continue; } var b = list[start]; var c = list[end]; if (a+b+c+d == target) { var v = new List<int>(){a,b,c,d}.OrderBy(x=>x).ToList(); var k = string.Join(",",v); if(!dic.ContainsKey(k)){ dic.Add(k,v); } start ++; end --; } else if (a+b+c+d > target){ end --; } else{ start ++; } } } } var ret = new List<IList<int>>(); foreach(var kv in dic){ ret.Add(kv.Value); } return ret; } }
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- hpuoj 1715: 感恩节KK专场——2015年的第一场雪 (暴力)
- stm32 实现串口中断接收浮点型、整型数据
- java基础之正则及面向对象
- volley解惑
- 浅谈三层架构
- LeetCode -- 4Sum
- iOS中的开发模式
- 启动其他应用
- 复选框与单选按钮
- 【C++ MFC开发】串口通信之多个编辑框输出
- opencv计算图像的水平投影和垂直投影
- LeetCode -- Binary Tree Level Order Traversal II
- 禅修程序员十诫
- 打开图片出现com surrogate 已停止工作