leetcode: 15. 3Sum
来源:互联网 发布:linux 查看最后500行 编辑:程序博客网 时间:2024/06/15 11:52
Problem
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero.## Note: The solution set must not contain duplicate triplets.## For example, given array S = [-1, 0, 1, 2, -1, -4],## A solution set is:# [# [-1, 0, 1],# [-1, -1, 2]# ]
AC
class Solution(): def threeSum(self, x): x.sort() res = [] for left in range(len(x) - 2): if left == 0 or x[left] != x[left-1] and x[left] <= 0: mid, right = left + 1, len(x) - 1 while mid < right: s = x[left] + x[mid] + x[right] if s == 0: res.append([x[left], x[mid], x[right]]) mid, right = mid + 1, right - 1 while mid < right and x[mid] == x[mid - 1]: mid += 1 while mid < right and x[right] == x[right + 1]: right -= 1 elif s < 0: mid += 1 else: right -= 1 return resif __name__ == '__main__': assert Solution().threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]] assert Solution().threeSum([1 ,1, 1, -2]) == [[-2, 1, 1]]
阅读全文
0 0
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- [leetcode] 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode - 15. 3Sum
- [LeetCode]15. 3Sum
- Leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- 【leetcode】15. 3Sum
- Leetcode - 15. 3Sum
- Tomcat7.0.42源码研读之BIO(七)
- Hive2.2.0安装
- Unsupported major.minor version 52.0 问题解决
- ConcurrentLinkedQueue的实现原理和源码分析
- L1-003. 个位数统计
- leetcode: 15. 3Sum
- 回首Java——八大排序以及冒泡排序,插入排序分析实现
- SpringMVC之分析HandlerMethodReturnValueHandler(一)
- php+mysql多字段模糊搜索
- 封装
- 实现组合的递归算法
- LeetCode——Single Numeber
- UML图
- 区块链为什么叫区块链