【LeetCode每天一题】3Sum(三数之和)

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

Example: Given array nums = [-1, 0, 1, 2, -1, -4],              A solution set is:      [         [-1, 0, 1],           [-1, -1, 2]   ]

思路


  我们先对数组进行排序,然后从第一个数字开始查找, 然后在后面的数组中查找是否有满足条件的(使用两个指针一个指向开头,一个指向尾部开始遍历)。时间复杂度为O(n*n), 空间复杂度为O(1)。

图示步骤

        

 

 

解决代码


 

 1 class Solution(object):
 2     def threeSum(self, nums):
 3         nums.sort()
 4         length = len(nums) 
 5         res_list = []
 6         for i in range(length - 2):                  # 以此下标的数字和其他进行匹配
 7             if i > 0 and nums[i] == nums[i - 1]:      # 如果和上一个数字相等,直接返回。 因为上一次已经查找过
 8                 continue
 9             start, end = i + 1, length-1             # 在后面的数组中设置起始指针和尾部指针
10             while start < end:                       
11                 tem = nums[i] + nums[start] + nums[end]
12                 if tem == 0:                                 # 如果三个数字之和等于0,将其进行添加
13                     res_list.append([nums[i], nums[start], nums[end]])          
14                    
15                     while start < end and nums[start] == nums[start+1]:    # 判断start下一个数字和当前数字是否相等,相等下移一位。不然会添加进重复的元素
16                         start += 1                                          
17                     while start < end and nums[end] == nums[end-1]:          # 判断end上一个数字和当前数字是否相等,相等则跳过。
18                         end -= 1
19                     start += 1
20                     end -= 1
21                 elif tem < 0:                                           # 和小于 0 的话,start进位
22                     start += 1
23                 else:                                                   # 和大于0的话,end减一
24                     end -= 1
25         return res_list

 

 

 

 


 

posted @ 2019-04-02 11:46  GoodRnne  阅读(128)  评论(0编辑  收藏  举报