码迷,mamicode.com
首页 > 编程语言 > 详细

3Sum Leetcode Python

时间:2015-01-17 10:02:22      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   array   

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)


第一种做法是DFS 其解是NP hard是通解所有sub array的问题,所以过不了test但是自己机子是可以跑的。先贴在这里,

class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def dfs(self,num,valuelist,start,solution):
        if  len(valuelist)==3 and valuelist not in solution:
            solution.append(valuelist)
        for index in range(start,len(num)):
            valuelist=valuelist+[num[index]]
            self.dfs(num,valuelist,index+1,solution)
            valuelist=valuelist[:len(valuelist)-1]
    def threeSum(self, num):
        solution=[]
        num.sort()
        self.dfs(num,[],0,solution)
        return solution
        
        

另外一种解法是O(n^2) 先把数组排列一下,用三个pointer,第一个pointer是在 i 制定现在找到的值,第二个pointer是left=i+1 第三个pointer是right=len(num)-1

当num[i]+num[left]+num[right]==0时候就得到想要的解。否则当和小于0时left=left+1 和大于0则right=right-1

This method‘s time complexity is O(n^2), we need to sort the array first, then we use three pointers, the first pointer is the index from 0 to len(num-1)

the second pointer is left=i+1 the third pointer is right=len(num)-1, while left<right we check the num[i]+num[left]+num[right] if the value is 0 we add it to the solution.

if sum is less than 0 we increase left otherwise decrease right.


class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        solution=[]
        num.sort()
        
        for i in range(len(num)-1):
            if i>0 and num[i]==num[i-1]:
                continue
            left=i+1
            right=len(num)-1
            while left<right:
                val=num[i]+num[left]+num[right]
                if val==0 and [num[i],num[left],num[right]] not in solution:
                    solution.append([num[i],num[left],num[right]])
                    left=left+1
                    right=right-1
                elif val<0:
                    left=left+1
                else:
                    right=right-1
        return solution
        


3Sum Leetcode Python

标签:leetcode   python   array   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/42803209

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!