3sum

3个数字相加,有几种可能性:
1、000
2、负负正
3、负正正
4、0负正
假设数组是排序好了的,以第一个数字为-target,第二个数字和第三个数字相加之和为target
显然第一个数字不可能为正,因为正正正没有办法加起来为0
因此思想是,数组排序,从前向后扫描数组,到正数之前停止,然后以扫描到的数字为-target,向后进行two sum找数字

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in range(len(nums)):
            if nums[i] > 0:
                break
            else:
                if i == 0 or nums[i] > nums[i-1]:
                    target = -nums[i]
                    dic = {}
                    j = i + 1
                    for k in range(j,len(nums)):
                        if target - nums[k] in dic:
                            temp = sorted([-target,nums[k],target-nums[k]])
                            if temp not in res:
                                res.append(temp)
                        else:
                            dic[nums[k]] = k
        return res
        
     ```       

但是时间过了

网络上找到了一种没有超过时间的做法:

class Solution:
def threeSum(self, num):
if len(num) <= 2:
return []
ret = []
tar = 0
num.sort()
i = 0
while i < len(num) - 2:
j = i + 1
k = len(num) - 1
while j < k:
if num[i] + num[j] + num[k] < tar:
j += 1
elif num[i] + num[j] + num[k] > tar:
k -= 1
else:
ret.append([num[i], num[j], num[k]])
j += 1
k -= 1
# folowing 3 while can avoid the duplications
while j < k and num[j] == num[j - 1]:
j += 1
while j < k and num[k] == num[k + 1]:
k -= 1
while i < len(num) - 2 and num[i] == num[i + 1]:
i += 1
i += 1
return ret

你可能感兴趣的:(3sum)