三数之和(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\]

相关推荐
aiguangyuan3 小时前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
季明洵3 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi4 小时前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL4 小时前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独
小小张说故事4 小时前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python
Yeats_Liao4 小时前
评估体系构建:基于自动化指标与人工打分的双重验证
运维·人工智能·深度学习·算法·机器学习·自动化
luoluoal4 小时前
基于python的医疗领域用户问答的意图识别算法研究(源码+文档)
python
only-qi4 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_25014 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
Shi_haoliu4 小时前
python安装操作流程-FastAPI + PostgreSQL简单流程
python·postgresql·fastapi