三数之和

题目:给定一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a+b+c?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如,给定数组nums=[-1,0,1,2,-1,-4],

满足要求的三元组集合为:

[

[-1,0,1],

[-1,-1,2]

]

解题思路:先对序列排序,因为要找三个数,每次遍历固定一个元素,然后根据三数之和调整其他两个数的位置,如果等于0,符合要求,若果大于0,小的数字右移,如果小于0,大的数字左移。遍历过程中注意跳过重复数字。

 1 class Solution:
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         #先对数组排序
 8         nums.sort()
 9         count = len(nums)
10         collect = []
11         for i in range(count):
12             left = i+1
13             right = count-1
14             #避免重复找同一个数据
15             if i >0 and nums[i] == nums[i-1]:
16                 left +=1
17                 continue
18             #数据按小到大排列,每次选取nums[i],在其后寻找符合a + b + c = 0的两个数据
19             while left < right:
20                 sum = nums[i] + nums[left] + nums[right]
21                 if sum == 0:
22                     col = [nums[i],nums[left],nums[right]]
23                     collect.append(col)
24                     left+=1
25                     right-=1
26                     #循环中nums[i]已确定,当再确定1个数时,另一个数也确定,左右端任一端出现重复均可跳过
27                     while nums[left] == nums[left-1] and left < right:
28                         left+=1
29                     while nums[right] == nums[right+1] and left < right:
30                         right-=1
31                 if sum<0:
32                     #如果和小于0,小的数字右移增大
33                     left+=1
34                 elif sum > 0:
35                     #如果和大于0,大的数字左移减小
36                     right-=1
37         return collect

测试模块:

1 nums=[-1,0,1,2,-1,-4]
2 a=Solution.threeSum(1,nums)
3 print(a)

该算法还有待优化

猜你喜欢

转载自www.cnblogs.com/zhibei/p/9215488.html