文心一言 Python编程之

给一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a+b+c=0?请你找出所有和为0且不重复的三元组。 注意:答案中不可以包含重复的三元组。

示例1: 输入:nums=-1,0,1,2,-1,-4 输出:\[-1,-1,2,-1,0,1]

示例2: 输入:nums = \[\] 输出:\[\]

示例3: 输入:nums = 0 输出:\[\]

文心一言编程如下(自带注释)

python 复制代码
def three_sum(nums):
    if len(nums) < 3:
        return []

    nums.sort()  # 对数组进行排序
    result = []

    # 遍历数组,固定第一个元素
    for i in range(len(nums) - 2):
        # 避免重复的三元组
        if i > 0 and nums[i] == nums[i - 1]:
            continue

            # 双指针法,在剩余部分寻找和为-nums[i]的两个数
        left = i + 1
        right = len(nums) - 1

        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                # 和太小,移动左指针
                left += 1
                # 避免重复的三元组
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
            elif total > 0:
                # 和太大,移动右指针
                right -= 1
                # 避免重复的三元组
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
            else:
                # 找到和为0的三元组
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                # 避免重复的三元组
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1

    return result


# 示例1
nums1 = [-1, 0, 1, 2, -1, -4]
print(three_sum(nums1))  

# 示例2
nums2 = []
print(three_sum(nums2))  

# 示例3
nums3 = [0]
print(three_sum(nums3))  
相关推荐
科技道人1 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry2 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵3 小时前
【无标题】
数据结构·算法
向日的葵0063 小时前
langchain的Tools教程(三)
python·langchain·tools
逝水无殇4 小时前
C# 异常处理详解
开发语言·后端·c#
言乐65 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
Kx_Triumphs5 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
YUS云生5 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习