15. 3Sum

本文介绍了一种解决三数之和问题的有效算法。通过首先对数组进行排序,然后使用双指针技巧来寻找所有唯一三元组,使得这三个数相加等于零。该算法巧妙地避免了重复解,并且效率高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
  • The solution set must not contain duplicate triplets.

public class Solution {
	public List<List<Integer>> threeSum(int[] nums) {
		Arrays.sort(nums);//sort进行排序
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		for(int i = 0; i < nums.length-2; i++) {
			if(i > 0 && (nums[i] == nums[i-1]))
				continue;//避免重复
			for(int j = i+1, k = nums.length-1; j < k;) {
				int sum = nums[i] + nums[j] + nums[k];
				if(sum == 0) {
					list.add(Arrays.asList(nums[i],nums[j],nums[k]));
					j++;k--;
					while((j < k) && (nums[j] == nums[j-1]))
						j++;//避免重复
					while((j < k) && (nums[k] == nums[k+1]))
						k--;//避免重复
				}else if (sum > 0)
					k--;//结果大于0,大数往里缩
				else
					j++;//结果小于0,小数往里缩
			}
		}
		return list;
	}
}
//大致思路就是先排序,然后第一个数从0到num.length-2遍历,后面俩数初始放在最前面和最后面,然后慢慢的向里面靠近。此算法打败了92.68%的人。

//发现很多算法题都是两边入手往里,或者找到中间值向外扩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值