leetcode 、两个数的和、三个数的和、python

1.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析:[x,y] ——>x+y=9,复杂度O(n**2);y=9-x...O(1)....loops....O(n),复杂度O(n)

代码:

class Solution:
    def twoSum(self,nums,target):
        dict1 = {nums[i]:i for i in range(len(nums))}
        dict2 = {i:target-nums[i] for i in range(len(nums))}
        twoSumShow = []
        for i in range(len(nums)):
            j = dict1.get(dict2.get(i))
            if (j is not None) and (j != i):
                twoSumShow = [i ,j]
                break
        return twoSumShow

   

2.

For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

分析1:(x,y,z)——>x+y+z=0,复杂度O(n**3);c = -(a+b)..set..O(1).....复杂度O(n**2) 

代码:

def treeSum(self,nums):
    if len(nums) < 3:
        return []
    nums.sort() 
    #sort方法,有利于判断是否重复    
    res = set()
    for i,v in enumerate(nums[:-2]):  
        #v是第一层遍历,先枚举v
        if i >= 1 and v == nums[i-1]:
            continue
        d = {}
        for x in nums[i+1:]:
            #再枚举x
            if x not in d:
                d[-v-x] = 1
                #判断-v-x是否存在
            else:
                res.add((v,-v-x,x))
    return map(list,res)
    #map去重后返回出去

分析2:sort, find,快排:Array,sort,....O(NlogN);有序的,然后loops:a,b从左边开始,c从右边开始

代码:

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

3.拓展(后续补充)

[1,2,3,4,-1,-2,-4,...n]  ;return [a,b,c,d,...z]   (a+b+c+d+..+z=0)

复杂度的减少,就是基本减少for循环。尽量减少遍历的次数。减少步骤。尽量向0和1的思维靠拢,毕竟电脑考虑的是0和1。

 

 

猜你喜欢

转载自blog.csdn.net/qq_21121571/article/details/88420854