当前位置:网站首页>【leetcode】剑指 Offer II 007. 数组中和为 0 的三个数(双指针)
【leetcode】剑指 Offer II 007. 数组中和为 0 的三个数(双指针)
2022-08-03 19:24:00 【friedrichor】
剑指 Offer II 007. 数组中和为 0 的三个数
给定一个包含 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]
输出:[]
提示:
- 0 < = n u m s . l e n g t h < = 3000 0 <= nums.length <= 3000 0<=nums.length<=3000
- − 1 0 5 < = n u m s [ i ] < = 1 0 5 -10^5 <= nums[i] <= 10^5 −105<=nums[i]<=105
题解
这道题其实是剑指 Offer II 006. 排序数组中两个数字之和 的进阶版,可以参考上道题的思路来进一步解决这道题。
方法一:穷举
具体实现略。
方法二:固定一个值 + 双指针
这个方法可以先看剑指 Offer II 006. 排序数组中两个数字之和 的【方法三:双指针】
首先把 nums 按从小到大排列,固定第一个值 i,0 - nums[i] 即为上一题的 target,然后剩下两个数的查找方法就用上一题双指针的方法即可。此外,这里还要注意去重的问题,因为题目中要求是 不重复 的三元组。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort() # 从小到大排序
length = len(nums)
for i in range(length - 2):
if i > 0 and nums[i] == nums[i-1]: # 去重
continue
low = i + 1
high = length - 1
while low < high:
if nums[i] + nums[low] + nums[high] == 0:
res.append([nums[i], nums[low], nums[high]])
while low < high: # 去重
low += 1
if nums[low] != nums[low - 1]:
break
while low < high: # 去重
high -= 1
if nums[high] != nums[high + 1]:
break
elif nums[i] + nums[low] + nums[high] > 0:
high -= 1
else:
low += 1
return res
在上一道题中还有个二分查找的方法,不过这题用二分法就需要遍历两次,且去重等条件的实现有些复杂,不推荐使用。
边栏推荐
- 「游戏建模干货」建模大师几步操作,学习经典,赶紧脑补一下吧
- 【C语言学习笔记(六)】分支与跳转(if、else、continue、break、switch)
- Unity gets the actual coordinates of the ui on the screen under the canvas
- Postgresql-xl全局快照与GTM代码走读(支线)
- Postgresql中的pg_memory_barrier_impl和C的volatile
- 红日安全内网渗透靶场-VulnStack-1
- Postgresql源码(65)新快照体系Globalvis工作原理分析
- Radondb mysql installation problems
- Force is brushed buckle problem for the sum of two Numbers
- FreeRTOS Intermediate
猜你喜欢
随机推荐
FreeRTOS中级篇
要想成为黑客,离不开这十大基础知识
docker mysql 容器中执行mysql脚本文件并解决乱码
Unity获取canvas 下ui 在屏幕中的实际坐标
普通用户如何利用小红书赚钱呢?小红书的流量是真的吗?
flex布局
Cobalt Strike (CS) 逆向初探
ECCV2022 | 用于视频问题回答的视频图Transformer
力扣刷题之求两数之和
设备树基本原理与操作方法
Force is brushed buckle problem for the sum of two Numbers
Confused!Ali was abused on the one hand, but was fortunate to be promoted to Huawei's technology, and successfully got the offer, with an annual salary of 40w
钱江摩托某型号产品ECU货不对版 消费者知情权应如何保障?
阿里二面:多线程间的通信方式有几种?举例说明
云图说丨初识华为云微服务引擎CSE
阿里巴巴政委体系-第九章、阿里政委启示录
C#将位图旋转90度
安装radondb mysql遇到问题
虚拟机vmware设置桥接模式上网
系统太多,多账号互通如何实现?









