15. 3Sum

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]
]


思路1
暴力穷举 o(n3)

思路2
a+b+c=0
c=-b-a
穷举找-a-b,然后找数组里有没有c,(用set,复杂度 o(1))
->o(n2)

// 思路2 效率低,主要有去重复的问题,(未解决)
vector<vector<int>> threeSum2(vector<int>& nums) {
	// 放入set中
	
	std::map<int, bool> setNums;
	std::set<vector<int>> result;
	for (auto num : nums) {
		setNums.insert(std::make_pair(num, false));
	}

	for (int a = 0; a < nums.size() - 1; a++) {
		for (int b = a + 1; b < nums.size(); b++) {
			int tempC = -nums[a] - nums[b];
			setNums.at(nums[a]) = true;
			setNums.at(nums[b]) = true; // 说明这是ab了不会是c了
			auto iterator = setNums.find(tempC);
			if (iterator != setNums.end() && setNums.at(tempC) == false) {
				vector<int> temp = { nums[a], nums[b], tempC };
				std::sort(temp.begin(), temp.end());
				result.insert(temp);
			}

			setNums.at(nums[a]) = false;
			setNums.at(nums[b]) = false;
		}
	}
	vector<vector<int>> result2(result.begin(), result.end());
	return result2;
}

思路3
先排序在找
sort :NlogN 块排
枚举a,b从后面一堆数的第一个开始,c从最后一个开始 (O(n))

  1. A+B+C<0 则B往右移
  2. A+B+C>0 则C往左移一格
    一直移到B=C,看有没有找到一个等于0的 O(N)
    时间复杂度 O(N2)
    在这里插入图片描述
vector<vector<int>> threeSum(vector<int>& nums) {
	std::vector<vector<int>> result;
	if (nums.empty()) {
		return result;
	}

	std::size_t n_size = nums.size();
	std::sort(nums.begin(), nums.end());
	for (int i = 0; i < n_size; ++i) {
		// all numbers from now on will be greater than 0, no point in continuing
		if (nums[i] > 0) break;

		// we have seen this number & combo before; skip 去重
		if (i > 0 and nums[i] == nums[i-1]) continue;

		int left = i+1, right = n_size - 1;
		while (left < right) {
			int sum = nums[i] + nums[left] + nums[right];
			if (sum < 0) {
				++left;
			} else if (sum > 0) {
				--right;
			} else {
				result.push_back({nums[i], nums[left], nums[right]});
				int last_left = nums[left], last_right = nums[right];
				// we have seen this number & combo before; skip 去重
				while (left < right && nums[left] == last_left) ++left;
				while (left < right && nums[right] == last_right) --right;
			}
		}

	}
	return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值