LeetCode - 3Sum
来源:互联网 发布:三国志2霸王的大陆java 编辑:程序博客网 时间:2024/05/24 06:42
LeetCode - 3Sum
The problem is described as following:
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)
My solution is as following:
class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def threeSum(self, num): i, num, result = 0, sorted(num), [] while i < len(num)-2: j, k = i+1, len(num)-1 while j < k: if num[i] + num[j] + num[k] < 0: j += 1 elif num[i] + num[j] + num[k] > 0: k -= 1 else: result.append((num[i], num[j], num[k])) j, k = j+1, k-1 while j < k and num[j] == num[j-1]: j += 1 while j < k and num[k] == num[k+1]: k -= 1 i += 1 while i < len(num)-1 and num[i] == num[i-1]: i += 1 return result
这里要注意的是首先通过排序来使查找更高效,每次找到可行解之后要为避免重复而进行重复元素的过滤。
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (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: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- Trie树学习记录
- Android重复layout解决方法总结
- 【机器学习】相关博客收集
- wamp常见问题【0xc0007b】【重装phpmyadmin】
- 简述RFID系统的时隙ALOHA算法的工作过程。
- LeetCode - 3Sum
- 博弈问题及SG函数(真的很经典)
- 排序算法值插入排序-数组版
- LeetCode 70 Climbing Stairs
- Mysql Workbench connection ssl not enable问题解决
- 经典面试题(三)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯
- 向这个哥们致敬。
- 循环链表
- 【FZU】Problem 2137 奇异字符串【后缀数组】