python-leetcode-三数之和

15. 三数之和 - 力扣(LeetCode)

python 复制代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()  # 排序
        n = len(nums)
        res = []

        for i in range(n):
            # 剪枝:如果当前数 > 0,三数之和不可能为 0
            if nums[i] > 0:
                break

            # 去重:跳过重复元素
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            # 双指针
            left, right = i + 1, n - 1

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

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

                    # 去重:跳过相同的 left 和 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 res   
相关推荐
QiZhang | UESTC6 分钟前
JAVA算法练习题day11
java·开发语言·python·算法·hot100
屁股割了还要学9 分钟前
【数据结构入门】排序算法(4)归并排序
c语言·数据结构·学习·算法·排序算法
Tisfy15 分钟前
LeetCode 0966.元音拼写检查器:三个哈希表实现
leetcode·字符串·散列表·题解·哈希表
努力学习的小廉30 分钟前
我爱学算法之—— 位运算(上)
c++·算法
ゞ 正在缓冲99%…1 小时前
leetcode35.搜索插入位置
java·算法·leetcode·二分查找
lifallen1 小时前
字节跳动Redis变种Abase:无主多写架构如何解决高可用难题
数据结构·redis·分布式·算法·缓存
feifeigo1231 小时前
星座SAR动目标检测(GMTI)
人工智能·算法·目标跟踪
WWZZ20251 小时前
视觉SLAM第10讲:后端2(滑动窗口与位子图优化)
c++·人工智能·后端·算法·ubuntu·机器人·自动驾驶
YuTaoShao2 小时前
【LeetCode 每日一题】36. 有效的数独
linux·算法·leetcode
IT古董2 小时前
【漫话机器学习系列】003.Agglomerative聚类
人工智能·算法·机器学习