力扣hot100 三数之和 双指针 细节去重

Problem: 15. 三数之和

文章目录

思路

👨‍🏫 参考

Code

⏰ 时间复杂度: O ( n 2 ) O(n^2) O(n2)

🌎 空间复杂度: O ( 1 ) O(1) O(1)

Java 复制代码
class Solution {
 	public List<List<Integer>> threeSum(int[] nums)
	{
		List<List<Integer>> res = new ArrayList<>();
		int len = nums.length;
		if (len < 3)
			return res;
		Arrays.sort(nums);// 升序排序

		for (int i = 0; i < len; i++)// i选一个数(三个数中最小的数)
		{
			if (nums[i] > 0)// 最小数已经 > 0,和不可能 == 0
				break;
			// 当前数和前一个数相同,去重
			if (i > 0 && nums[i] == nums[i - 1])
				continue;

			int l = i + 1;// 选取第二个数(中间的数)
			int r = len - 1;// 选取第三个数(最大的数)
			while (l < r)
			{
				int sum = nums[i] + nums[l] + nums[r];
				if (sum == 0)
				{
					res.add(Arrays.asList(nums[i], nums[l], nums[r]));
//					 去重 l 和 r 的数
//					跳过重复的值,避免重复解
//					例:[0,-2,-2,-1,1,2,2]  中的 -2 -2 2 2 就需要去重
					while (l < r && nums[l] == nums[l + 1])
						l++;
					while (l < r && nums[r] == nums[r - 1])
						r--;
//					走到这,l 是连续相同段的最后一个,r 是连续相同段的第一个
//					再跳一次,把 nums[l] nums[r] 跳过
					l++;
					r--;
				} else if (sum < 0)// 左边的值 调大一点
					l++;
				else if (sum > 0)// 右边的值 调小一点
					r--;
			}
		}
		return res;
	}
}
相关推荐
To_OC7 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎8 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC9 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn9 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹10 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
雪碧聊技术10 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
麻雀飞吧10 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
CV-Climber13 小时前
检索技术的实际应用
人工智能·算法