LeetCode -- Three Sum
来源:互联网 发布:视频传输软件 编辑:程序博客网 时间:2024/04/29 08:27
问题描述: 在一个序列中找到3个数和等于N的所有组合(3个数升序排列,去重)
思路:
1 内循环使用two pointer ,从两端往中间找,判断和分别等于,小于,大于0的情况
2 外循环逐个后移
3 使用字典存键值=三个数的升序排列,解决重复问题
最坏情况: O(N²)
实现代码:
public IList<IList<int>> ThreeSum(int[] nums){ if(nums == null || nums.Length < 3){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 i = 0 ;i <= len - 3 ;i++){var a = list[i];var start = i+1;var end = len-1;while (start < end) {var b = list[start];var c = list[end];if (a+b+c == 0) {var v = new List<int>(){a,b,c}.OrderBy(x=>x).ToList();var k = string.Join(",",v);if(!dic.ContainsKey(k)){dic.Add(k,v);}start ++;end --;}else if (a+b+c > 0){end --;}else{start ++;}}}var ret = new List<IList<int>>();foreach(var kv in dic){ret.Add(kv.Value);}return ret;}
0 0
- 【Leetcode】three sum
- [LeetCode] Three Sum
- LeetCode -- Three Sum
- leetcode#15 Three Sum
- leetcode(M) three sum
- leetcode-15.Three Sum
- Three Sum || LeetCode-15
- LeetCode- Three Sum
- [LeetCode] Three Sum题解
- Three Sum -- LeetCode [数组类]
- Leetcode Exercise 1:Two Sum + Three Sum
- LeetCode (1) Two Sum (15)Three sum (16)Three sum closest (17)Four sum
- [Leetcode P15] Three Sum 三数之和
- Three Sum
- THREE SUM
- three sum
- THREE SUM
- Three Sum
- 青蛙跳台阶
- 图像处理函数详解——padarray
- java 多线程------条件变量
- Java多线程
- hdu1969 pie【二分】
- LeetCode -- Three Sum
- Object-C NSURL
- UML学习
- android给其他App发送简单的数据
- C++中this指针的用法详解
- 关于STM32栈增长和大端/小端问题是和CPU相关的两个问题
- RPC深入浅出
- 欢迎使用CSDN-markdown编辑器
- VS2012编译Lua5.3.1