问题描述

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

解决方案

class Solution:
def threeSum(self, nums): res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append((nums[i], nums[l], nums[r]))
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
return res data = [1, 2, -1, -2, 3, 0, 5, -3]
sk = Solution()
print(sk.threeSum(nums=data))

最新文章

  1. XML文件数据操作
  2. ssh框架介绍
  3. (转)Android系统自带Activity样式(@android:style/)
  4. 编译Apache Hadoop2.2.0源代码
  5. does not support ASP.NET compatibility 错误
  6. Ubuntu中使用pyUSB读取鼠标或键盘的数据程序
  7. 《sift算法详解》阅读笔记
  8. HDU 2064 菜鸡第一次写博客
  9. Java反射机制深度剖析
  10. php+mysql 除了设置主键防止表单提交内容重复外的另一种方法
  11. (转)每天一个linux命令(15):tail 命令
  12. Error:Failed to load project configuration:xxxxxxxxxxxxxxxxxxxx cannot read file .idea/misc.xml
  13. 混合app
  14. django-Ajax发送POST请求(csrf跨站请求的三种方式),文件的上传
  15. Python基础之面向对象思维解决游戏《天龙八部》
  16. python魔法方法、构造函数、序列与映射、迭代器、生成器
  17. Elasticsearch5.x创建索引(Java)
  18. PHP中json数组与对象的问题
  19. 数据初始化:有则更新无则添加(mySql,oracle)
  20. java集合系列之三(ArrayList)

热门文章

  1. Centos系统压力测试 ab 命令安装与使用
  2. angular-cli ng build 打包完成后 打开文件显示空白
  3. 20165206 2017-2018-2 《Java程序设计》第二周学习总结
  4. STL用法大全
  5. C# Enum 类型遍历
  6. WPF编程之找不到资源mainWindow.xaml
  7. python--使用双向队列结构检查回文
  8. DBEntityEntry类
  9. [转] 组件库按需加载 借助babel-plugin-import实现
  10. [转]sqlplus /nolog 出错解决 SP2-0667: Message file sp1&lt;lang&gt;.msb not found SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory