leetcode-15. 三数之和

[15] 三数之和
https://leetcode-cn.com/problems/3sum/description/

algorithms
Medium (23.65%)
Likes: 1259
Dislikes: 0
Total Accepted: 83.6K
Total Submissions: 352.8K
Testcase Example: '[-1,0,1,2,-1,-4]'

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

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

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

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

整体思路:

  1. 三元组和 == 0,三元组假设为: nums[i], nums[j], nums[k], 先确定下来一个数nums[i]
  2. 问题就变成找到两个数 nums[j] + nums[k] == -nums[i] 即还是可以写成nums[i] + nums[j] + nums[k] == 0
  3. 重点是排序之后先确定一个数,然后利用双指针遍历数组,注意去重
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []        # 需要返回的结果集
        nums.sort()     # 先排序,后面使用双指针
        for index in range(len(nums) - 2):      # 先选定一个元素
            if index > 0 and nums[index] == nums[index - 1]:    # 去重
                continue
            i = index + 1   # 左指针
            j = len(nums) - 1   # 右指针
            while i < j:    # 双指针循环
                if nums[i] + nums[j] + nums[index] > 0:
                    j -= 1 
                elif nums[i] + nums[j] + nums[index] < 0:
                    i += 1
                else:   # 找到符合条件的三个数
                    res.append([nums[i], nums[j], nums[index]]) # 加入结果集
                    i += 1  # 左指针右移
                    j -= 1  # 右指针左移
                    # 下面这里需要注意,避免重复
                    while i < j and nums[i] == nums[i - 1]:
                        i += 1
                    while j > i and nums[j] == nums[j + 1]:
                        j -= 1

        return res            
posted @ 2019-08-23 01:25  芝士粉子  阅读(124)  评论(0编辑  收藏  举报