题目来源于leetcode(https://leetcode.com/problems/3sum/description/)
3Sum
Given an array nums of n integers, are there elements a, b, c in nums 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 containduplicate triplets.
Example:
Given array nums =[-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
这道题目有一个输入:一串整型数的列表。取列表中三个数相加,若结果为零,则将这三个数放入输出的列表中。
设计思路:
利用三个循环,遍历所有可能的结果,最后输出正确答案
代码如下:
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
l=[]
for i in range(len(nums)):
if i<len(nums)-2:
for j in range(i+1,len(nums)):
if i<len(nums)-1:
for k in range(j+1,len(nums)):
if nums[i]+nums[j]+nums[k]==0:
l1=[nums[i],nums[j],nums[k]]
l1.sort()
if len(l)==0:
l.append(l1)
else:
judge=1
for l_ in l:
if l_==l1:
judge=0
if judge==1:
l.append(l1)
return l
然而三个循环的时间复杂度是O(n^3),并不能通过leetcode的标准测试,得到TLE的错误。
在discussion中看到了一个非常值得学习的算法。
作者caikehe
代码如下:
def threeSum(self, nums):
res = []
nums.sort()
for i in xrange(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
他在第二层循环中同时对列表的前后端元素相加判断,由于列表是有序的,因此这样的遍历是有效的。将复杂度降低到O(n^2)。
2018/5/4