35.leetcode15_3Sum

1.题目描述

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.

如果S中有a,b,c满足a+b+c==0,返回所有的满足这个条件的[a,b,c],而且不能重复

2.题目分析

如果采用暴力搜索法,三指针从头至尾依次遍历所有元素,那么复杂度为O(n3);如果先将S排序,先固定一个元素,然后再双指针分别从固定元素之后的首元素和末元素开始遍历,时间复杂度为O(n2)

3.解题思路

找出所有的[a,b,c]组合不难,难点就在如何避免重复的[a,b,c]。一开始采用的是not in进行搜索,然后超时了。

①失败的代码:

 1 class Solution(object):
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         result=[]
 8         temp=[]
 9         nums.sort()
10         i=0
11         l=len(nums)
12         while i<l-2:
13             left=i+1
14             right=l-1
15             if nums[i]>0 or nums[right]<0:
16                 break
17             while left<right and nums[left]+nums[i]<=0 and nums[right]>=0:
18                 s=nums[i]+nums[left]+nums[right]
19                 if s==0 and [nums[i],nums[left],nums[right]] not in result: #问题就在这里,not in 使搜索的复杂度随着result元素的增加而增加
20                     temp=[nums[i],nums[left],nums[right]]
21                     result.append(temp)
22                     left+=1
23                     right-=1
26                 elif s>0:
27                     right-=1
28                 else:
29                     left+=1
30             i+=1
31         return result

昨天晚上找了一个小时没有发现这个bug,ε=(´ο`*)))唉。今天早晨明白这个bug以后,重新改了一下。

②成功的代码

 1 class Solution(object):
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         result=[]
 8         nums.sort()
 9         l=len(nums)
10         for i in range(0,l-2):
11             if i>0 and nums[i]==nums[i-1]: #遇见重复的元素,直接跳过就好了
12                 continue
13             left=i+1
14             right=l-1
15             if nums[i]>0 or nums[right]<0:
16                 break
17             while left<right and nums[left]+nums[i]<=0: #不需要not in搜索result数组元素
18                 s=nums[i]+nums[left]+nums[right]
19                 if s==0:
20                     result.append([nums[i],nums[left],nums[right]])
21                     left+=1
22                     right-=1
23                     while left<right and nums[left]==nums[left-1]:left+=1 #跳过
24                     while left<right and nums[right]==nums[right+1]:right-=1 #跳过
25                 elif s>0:
26                     right-=1
27                 else:
28                     left+=1
29         return result   

 

posted @ 2018-02-24 09:35  vlice  阅读(79)  评论(0编辑  收藏  举报