[LeetCode] 三数之和

Given an array S of n integers, are there elements abc 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)
我们对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了。这里我们可以先做个剪枝优化,就是当遍历到正数的时候就break,为啥呢,因为我们的数组现在是有序的了,如果第一个要fix的数就是正数了,那么后面的数字就都是正数,
就永远不会出现和为0的情况了。然后我们还要加上重复就跳过的处理,处理方法是从第二个数开始,如果和前面的数字相等,就跳过,因为我们不想把相同的数字fix两次。对于遍历到的数,用0减去这个fix的数得到一个target,然后只需要再之后找到两个数之和等于target即可。
我们用两个指针分别指向fix数字之后开始的数组首尾两个数,如果两个数和正好为target,则将这两个数和fix的数一起存入结果中。然后就是跳过重复数字的步骤了,两个指针都需要检测重复数字。如果两数之和小于target,则我们将左边那个指针i右移一位,使得指向的数字增大一些。
同理,如果两数之和大于target,则我们将右边那个指针j左移一位,使得指向的数字减小一些,代码如下:
class Solution:
    def threeSum(self, nums):
        sortednums = sorted(nums)
        if len(nums) < 3 : return []
        if sortednums[0] > 0 or sortednums[-1]< 0 : return []
        if sortednums[0] == sortednums[-1] == 0 : return [[0,0,0]]
        res = []
        i=0
        while i < len(sortednums)-2:
#当遍历到正数的时候就break,因为后面全是正数了,不会出现和为0的情况了
            if sortednums[i] >0:
                break          
            j,k = i+1,len(sortednums)-1            
            while j < k:
                sum = sortednums[j] + sortednums[k]
                if sum > -sortednums[i]:
                    k-=1
                elif sum < -sortednums[i]:
                    j+=1
                else:
                    res.append([sortednums[i], sortednums[j], sortednums[k]])                    
                    #如果和前面的数字相等,就跳过,避免重复处理
                    tempj = sortednums[j]
                    while j < k and sortednums[j] == tempj: #j避免重复
                        j+=1
                    tempk = sortednums[k]
                    while j < k and sortednums[k] == tempk: #k避免重复
                        k-=1
            tempi = sortednums[i]
            while i < len(sortednums)-2 and sortednums[i] == tempi : #i避免重复
                i += 1
        return res

对于二数求和问题:

我们可以事先将数组数存储起来,使用一个HashMap,来建立数字和其坐标位置之间的映射,我们都知道HashMap是常数级的查找效率。这样,我们在遍历数组的时候,用target减去遍历到的数字,就是另一个需要的数字了,直接在HashMap中查找其是否存在即可。注意要判断查找到的数字不是第一个数字,比如target是4,遍历到了一个2,那么另外一个2不能是之前那个2,整个实现步骤为:先遍历一遍数组,建立HashMap映射,然后再遍历一遍,开始查找,找到则记录index。时间复杂度:O(n)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """           
        n = len(nums)
        #创建一个空字典
        d = {}
        for x in range(n):
            a = target - nums[x]
            #字典d中存在nums[x]时
            if nums[x] in d:
                return d[nums[x]],num[x]
            #否则往字典增加键/值对
            else:
                d[a] = num[x]
        #边往字典增加键/值对,边与nums[x]进行对比

 

原文地址:https://www.cnblogs.com/USTC-ZCC/p/10629678.html