3sum(leetcode)
来源:互联网 发布:淘宝网全屏轮播代码 编辑:程序博客网 时间:2024/06/12 14:05
题目:
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)
解题思路1:
使用最为朴素的方法,即为3个for循环进行遍历。但时间复杂度为O(n**3)。无法通过测试
代码:
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
def swap(i,j,k):
l=[i,j,k]
r return sorted(l)
list = []
n = len(num)
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(j+1,n):
list_tmp = swap(num[i],num[j],num[k])
if num[i]+num[j]+num[k]==0 and list_tmp not in list:
list.append(list_tmp)
return list
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
def swap(i,j,k):
l=[i,j,k]
r return sorted(l)
list = []
n = len(num)
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(j+1,n):
list_tmp = swap(num[i],num[j],num[k])
if num[i]+num[j]+num[k]==0 and list_tmp not in list:
list.append(list_tmp)
return list
解题思路2:
首先对数组进行排序,然后再进行类似二分的夹逼搜索。时间复杂度为O(n**2)
代码:
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
n = len(num)
ans =[]
num = sorted(num)
for i in range(n-2):
low = i+1
high = n-1
while low<high:
if num[low]+num[high]+num[i]==0 and [num[i],num[low],num[high]] not in ans:
ans.append([num[i],num[low],num[high]])
low += 1
elif num[low]+num[high]+num[i]<0:
low += 1
continue
elif num[low]+num[high]+num[i]>0:
high -= 1
continue
else:
low += 1
return ans
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
n = len(num)
ans =[]
num = sorted(num)
for i in range(n-2):
low = i+1
high = n-1
while low<high:
if num[low]+num[high]+num[i]==0 and [num[i],num[low],num[high]] not in ans:
ans.append([num[i],num[low],num[high]])
low += 1
elif num[low]+num[high]+num[i]<0:
low += 1
continue
elif num[low]+num[high]+num[i]>0:
high -= 1
continue
else:
low += 1
return ans
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
- 概率图模型
- 的风格和士大夫是个花洒的规划撒飞嘎方式噶峰会上
- Jboss加载不到数据库驱动问题解决过程记录
- Android性能优化
- Linux查看用于终止进程命令
- 3sum(leetcode)
- HDU 2087剪花布条
- ny1112求次数(map容器)
- ios
- Android 使用线程更新UI(附带计时器demo)
- 日拱一卒(十一)
- Apache Log4j 架构之二 总体架构
- Swift语法基础:18 - Swift的元组, 绑定值, Where
- WebRTC学习与DEMO资源一览