15. 三数之和(中)
题目
-
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
示例 2:
输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。
示例 3:
输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。
python
题解:排序+三指针
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
res = []
if not nums or n < 3: # 如果列表为空或者长度小于3,直接返回空列表
return []
nums.sort() # 对列表进行排序,方便后续使用双指针法
res = []
for i in range(n):
if nums[i] > 0: # i对应的数在排序后是最小的,如果当前数大于0,则无法凑成和为0的三元组,直接返回结果
return res
if i > 0 and nums[i] == nums[i - 1]: # 跳过重复的数字,避免重复计算
continue
L = i + 1 # 左指针初始位置
R = n - 1 # 右指针初始位置
while L < R:
if nums[i] + nums[L] + nums[R] == 0: # 找到和为0的三元组
res.append([nums[i], nums[L], nums[R]])
while L < R and nums[L] == nums[L + 1]: # 跳过左指针重复的数字
L = L + 1
while L < R and nums[R] == nums[R - 1]: # 跳过右指针重复的数字
R = R - 1
L = L + 1 # 在已经找到和为0的情况下,左右指针进行更新
R = R - 1
elif nums[i] + nums[L] + nums[R] > 0: # 三数之和大于0,说明右指针的数太大,需要左移右指针
R = R - 1
else: # 三数之和小于0,说明左指针的数太小,需要右移左指针
L = L + 1
return res
JavaScript
题解:排序+三指针
var threeSum = function(nums) {
//先排序、i指针、左指针、右指针
//三个指针对应的值和为0加入结果集、并且继续找:同时移动左右指针
//如果和的值大于0,左移右指针;小于0右移左指针
//每一次都对左指针的右一位、右指针的左一位进行判断,相等移动
// nums = nums.sort()//按字符串 Unicode 编码排序[ -1, -1, -4, 0, 1, 2 ]
//a - b<0时a排b前;a - b>0时a排b后面
nums.sort((a, b) => a - b)//[ -4, -1, -1, 0, 1, 2 ]
let res=[]
for(let i=0;i<nums.length;i++){
if(nums[i]>0){
return res
}
if(i>0 && nums[i]==nums[i-1]){
continue
}
let L = i+1
let R = nums.length-1
while(L<R){
if(nums[i]+nums[L]+nums[R]==0){
res.push([nums[i],nums[L],nums[R]])
while(nums[L+1]==nums[L]){
L=L+1
}
while(nums[R]==nums[R-1]){
R=R-1
}
R--
L++
}else if(nums[i]+nums[L]+nums[R]>0){
R--
}else{
L++
}
}
}
return res
};
标签:
力扣
, 力扣hot100-js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2021-01-25 pyplot绘图