三数之和(LeetCode)

题目

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != kj != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

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

解题

python 复制代码
def threeSum(nums):
    nums.sort()  # 首先对数组进行排序
    result = []  # 用于存储最终结果的列表

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            # 避免重复的三元组
            continue

        left, right = i + 1, len(nums) - 1

        while left < right:
            total = nums[i] + nums[left] + nums[right]

            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                # 找到一个和为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

    return result


# 示例
nums = [-1, 0, 1, 2, -1, -4]
print(threeSum(nums))

\[-1, -1, 2\], \[-1, 0, 1\]

相关推荐
地平线开发者14 小时前
征程 6 | 灰度图部署链路介绍
算法·自动驾驶
Blossom.11814 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
地平线开发者14 小时前
手撕大模型|KVCache 原理及代码解析
算法·自动驾驶
蒋星熠14 小时前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu14 小时前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
cellurw15 小时前
EDID 数据结构解析与编辑工具:校验和计算、厂商/设备名编解码、物理地址读写、颜色与时序信息提取
数据结构
Q_Q196328847515 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
共享家952715 小时前
经典动态规划题解
算法·leetcode·动态规划
Pluchon15 小时前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
Rhys..15 小时前
.gitignore文件的作用及用法
python·github