leetcode#15

给定一个整数数组nums,找出所有和为0的不重复的三元组。要求先对数组进行排序,然后通过固定一个元素,使用双指针法寻找其余两个元素,确保结果不重复。例如,输入[-1, 0, 1, 2, -1, -4],输出为[[-1, 0, 1], [-1, -1, 2]]。" 124066634,13388261,Selenium自动化测试:文件上传实战指南,"['selenium', '自动化测试', 'pywin32']
摘要由CSDN通过智能技术生成

==============================================================================

【id】#15

【title】 3Sum

【description】

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]
]

【idea】
双指针!!!!!极其特别重要的方法!!
首先将数组排序得到有序数组。
然后找到一个固定的数,另外两个数加和为固定数的相反数。因为数组是有秩序的,所以固定数必须是非负数,因为如果是正数,后边的所有数都是正数,不会加和为负数。

找到固定数之后,固定数之后的数组手尾为两个指针,如果加和为target,移动指针,并且忽略掉相同的元素避免最后结果重复。

【code】

class Solution(object):
    def threeSum(self, nums):
        if len(nums) <3 : return []
        nums = sorted(nums)
        # print(nums)
        length = len(nums)
        res = []
        for i in range(length):
            if nums[i] > 0 : break
            if i >0 and nums[i] == nums[i-1]: continue
            target = -nums[i]
            # print(target)
            low = i+1
            high = length-1
            while high >low:
                if nums[low] + nums[high] == target :
                    res.append([nums[i],nums[low], nums[high]])
                    while low <high and nums[low] == nums[low+1]: low += 1
                    while low <high and nums[high] == nums[high-1]: high -= 1
                    low += 1
                    high -= 1
                elif nums[low] + nums[high] > target: high -= 1
                else: low += 1

        return res


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值