Leetcode15. 3 sum(C++,排序+双指针)

参考:https://www.cxyxiaowu.com/410.html


题目描述:

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

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]


3sum有三种处理方法,三重遍历,哈希遍历,排序+双指针。

重点在于如何处理重复集合。
需要特别注意的是,对集合中元素少于3个时,要做特殊处理。


class Solution {

public:

void TwoSum(vector<int> nums, int target, int StartIndex, vector<vector<int>>& results) {
	int left = StartIndex;
	int right = nums.size() - 1;
	vector<int> result;
	while (left < right) {
		if (nums[left] + nums[right] < target)left++;
		else if (nums[left] + nums[right] > target)right--;
		else {
			result.push_back(nums[left]);
			result.push_back(-target);
			result.push_back(nums[right]);

			results.push_back(result);
			left++; right--;
			while (left < right && nums[left] == nums[left - 1])
			{
				left++;
			}
			while (left < right && nums[right] == nums[right + 1])
			{
				right--;
			}
			result.clear();
		}
	}
}

vector<vector<int>> threeSum(vector<int>& nums) {
	vector<vector<int>> results;
	if (nums.size() <= 2)return results;
	sort(nums.begin(), nums.end());
	
	for (int i = 0; i < nums.size() - 2; i++) {
		if (i>=1&&nums[i] == nums[i-1])
		{
			continue;
		}
		TwoSum(nums, -nums[i], i + 1, results);
	}
	return results;
}

};

避免处理相同元素(会出现相同的集合)的两个操作:

①在遍历时:

		if (i>=1&&nums[i] == nums[i-1])
		{
			continue;
		}

②在寻找元素时:

			while (left < right && nums[left] == nums[left - 1])
			{
				left++;
			}
			while (left < right && nums[right] == nums[right + 1])
			{
				right--;
			}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值