[LintCode 57] 三数之和(Python)
来源:互联网 发布:华为mate8root权限软件 编辑:程序博客网 时间:2024/05/19 22:58
题目描述
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
注意事项
在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。
样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)
思路
先对序列排序。因为要找三个数,每次遍历固定一个元素,然后根据三数之和调整其他两个数的位置。如果等于0,符合要求;如果大于0,小的数字右移;如果小于0,大的数字左移。遍历过程中注意跳过重复出现的数字。
代码
class Solution: """ @param: numbers: Give an array numbers of n integer @return: Find all unique triplets in the array which gives the sum of zero. """ def threeSum(self, numbers): # write your code here if numbers is None or len(numbers) < 3: return [] res = [] numbers.sort() s = 0 e = len(numbers) - 1 while s < e: a = numbers[s] j = s + 1 k = e while j < k: b = numbers[j] c = numbers[k] if a + b + c == 0: res.append([a, b, c]) if a + b + c <= 0: while b == numbers[j] and j < k: j += 1 if a + b + c >= 0: while c == numbers[k] and j < k: k -= 1 while a == numbers[s] and s < e: s += 1 return res
复杂度分析
时间复杂度
阅读全文
0 0
- [LintCode 57] 三数之和(Python)
- lintcode-三数之和-57
- LintCode 57-三数之和
- lintcode(57)三数之和
- LintCode 57 三数之和
- LintCode 三数之和
- LintCode 三数之和
- LintCode: 三数之和
- lintcode,三数之和
- Lintcode 三数之和
- [Lintcode]三数之和
- lintcode--三数之和
- lintcode 三数之和
- LintCode(M)三数之和
- LintCode两数之和,三数之和,四数之和
- 【lintcode】两数之和、三数之和、最接近的三数之和、四数之和小结
- LintCode 三数之和(二)
- 三数之和——LintCode
- mac下的一些有用的命令收集,希望有时间不断完善
- tomcat 不使用ROOT 使用server.xml配置 去除项目名 使用80端口访问项目
- mysql 常用的function
- 自定义数组列表和队列
- tablayout/viewpager/fragment
- [LintCode 57] 三数之和(Python)
- Windows桌面共享中一些常见的抓屏技术
- 错误集锦
- 网络安全/端口
- 怎么复制Windows命令行模式界面中的内容?
- 磁盘iops 测试
- Introduction NFS, or Network File System, is a distributed filesystem protocol that allows you to m
- es6 变量的解构赋值
- ios实现mapbox源代码编译