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

相关推荐
Access开发易登软件7 小时前
Access调用Azure翻译:轻松实现系统多语言切换
后端·python·低代码·flask·vba·access·access开发
yumgpkpm7 小时前
CMP (类Cloudera) CDP7.3(400次编译)在华为鲲鹏Aarch64(ARM)信创环境中的性能测试过程及命令
大数据·hive·hadoop·python·elasticsearch·spark·cloudera
Rubisco..7 小时前
牛客周赛 Round 111
数据结构·c++·算法
兮山与7 小时前
算法8.0
算法
高山上有一只小老虎7 小时前
杨辉三角的变形
java·算法
Swift社区7 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato7 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
hz_zhangrl7 小时前
CCF-GESP 等级考试 2025年9月认证C++四级真题解析
开发语言·c++·算法·程序设计·gesp·c++四级·gesp2025年9月
代码小菜鸡6667 小时前
java 常用的一些数据结构
java·数据结构·python
火山灿火山8 小时前
详解AVL树旋转操作实现
数据结构·c++