LeetCode 15 3Sum 解题思路和python代码

题目:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

Explanation:

nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.

nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.

nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.

The distinct triplets are [-1,0,1] and [-1,-1,2].

Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]

Output: []

Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]

Output: [[0,0,0]]

Explanation: The only possible triplet sums up to 0.

Constraints:

3 <= nums.length <= 3000

-105 <= nums[i] <= 105

解题思路:

首先对数组进行排序,有助于使用双指针方法快速找到合适的三元组。

对于每个元素nums[i],将它作为第一个数,然后使用双指针方法在 i 之后的数组部分寻找另外两个数,使它们的和等于0。

左指针从 i+1 开始,右指针从数组末尾开始,逐步向中间收缩。根据三者之和的结果,调整左右指针的位置。

为了避免重复的三元组,遍历时需要跳过相同的元素。

python 复制代码
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()

        print("nums: ", nums)

        for i in range(len(nums)):
            print("i: ", i)

            # 如果当前元素和前一个相同,跳过,避免重复三元组
            if i > 0 and nums[i] == nums[i-1]:
                continue
            
            left, right = i+1, len(nums)-1

            while left < right:
                print("nums[i]: ", nums[i])
                print("nums[left]: ", nums[left])
                print("nums[right]: ", nums[right])
                total = nums[i] + nums[left] + nums[right]
                print("total: ", total)

                if total == 0:
                    result.append([nums[i], nums[left], nums[right]])

                    while left < right and nums[left] == nums[left+1]:
                        left+=1
                    while left < right and nums[right] == nums[right-1]:
                        right-=1
                    
                    left+=1
                    right-=1
                
                elif total < 0:
                    left += 1
                else:
                    right -= 1
        
        return result

例子:

nums = [-1,0,1,2,-1,-4]

首先,对数组进行排序。

('nums: ', [-4, -1, -1, 0, 1, 2])

接着,遍历数组。

('i: ', 0)

('nums[i]: ', -4)

('nums[left]: ', -1)

('nums[right]: ', 2)

('total: ', -3)

和小于0,说明左指针太小,向右移动左指针。

('nums[i]: ', -4)

('nums[left]: ', -1)

('nums[right]: ', 2)

('total: ', -3)

和还是小于0,说明左指针太小,向右移动左指针。

('nums[i]: ', -4)

('nums[left]: ', 0)

('nums[right]: ', 2)

('total: ', -2)

和还是小于0,说明左指针太小,向右移动左指针。

('nums[i]: ', -4)

('nums[left]: ', 1)

('nums[right]: ', 2)

('total: ', -1)

和还是小于0,但 i=0 的遍历结束,进入 i=1。

('i: ', 1)

('nums[i]: ', -1)

('nums[left]: ', -1)

('nums[right]: ', 2)

('total: ', 0)

和等于0,将三元组加入result。检查左指针指向的数(-1)是否与下一个数(0)相等,如果相等,就要跳过重复的左指针元素;同样道理,检查右指针指向的数(2)是否与前一个数(1)相等,如果相等,就跳过重复的右指针元素。

移动指针后,继续计算和。

('nums[i]: ', -1)

('nums[left]: ', 0)

('nums[right]: ', 1)

('total: ', 0)

和等于0,将三元组加入result。

左指针大于右指针,遍历结束。

('i: ', 2)

nums[2]还是 -1,因此跳过。

('i: ', 3)

('nums[i]: ', 0)

('nums[left]: ', 1)

('nums[right]: ', 2)

('total: ', 3)

左指针大于右指针,遍历结束。

('i: ', 4)

左指针等于右指针,while loop不会开始。

('i: ', 5)

左指针大于右指针,while loop不会开始。

output是 [[-1,-1,2],[-1,0,1]]

time complexity是O(n^2)

相关推荐
金融小师妹8 分钟前
AI多因子模型解析:黄金涨势受阻与美联储9月降息政策预期重构
大数据·人工智能·算法
R-G-B14 分钟前
【P38 6】OpenCV Python——图片的运算(算术运算、逻辑运算)加法add、subtract减法、乘法multiply、除法divide
人工智能·python·opencv·图片的运算·图片加法add·图片subtract减法·图片乘法multiply
数据智能老司机21 分钟前
MCP 实战——全局视角:为什么 MCP 将成为 AI 的颠覆者
python·llm·mcp
在星空下27 分钟前
Fastapi-Vue3-Admin
前端·python·fastapi
cxyll123434 分钟前
从接口自动化测试框架设计到开发(三)主流程封装、返回数据写入excel
前端·python·excel
Kyln.Wu38 分钟前
【python实用小脚本-190】Python一键删除PDF任意页:输入页码秒出干净文件——再也不用在线裁剪排队
服务器·python·pdf
NAGNIP1 小时前
LLaMA 3:离 AGI 更近一步?
算法
PineappleCoder1 小时前
力扣【2348. 全0子数组的数目】——从暴力到最优的思考过程
前端·javascript·算法
九章云极AladdinEdu1 小时前
Scikit-learn通关秘籍:从鸢尾花分类到房价预测
人工智能·python·机器学习·分类·scikit-learn·gpu算力
_poplar_2 小时前
08.5【C++ 初阶】实现一个相对完整的日期类--附带源码
c语言·开发语言·数据结构·c++·vscode·算法·vim