LeetCode#15. 3Sum

Given an array nums of n integers, are there elements abc 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]
]

问题大意:给定一个数组,求所有满足条件的三个数a,b,c,使得a+b+c=0  (结果要去重)

解决方案:排序。枚举第一个数,然后双指针,复杂度O(n^2) . 注意在过程中顺便去重。比如双指针中,找到满足条件的解了,L<R && nums[L] == nums[L-1],进行 L++

#include<vector>
#include<iostream>
#include<map>
#include<iterator>
#include<algorithm>
using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {
	//相对数组进行排序
	sort(nums.begin(), nums.end());
	vector<vector<int>> ans;
	//遍历每个元素
	for (int i = 0; i < nums.size(); ++i){
		//如果当前指针所指元素连续,则指针向前移动一位
		if (i > 0 && nums[i] == nums[i - 1]) continue;
		//left指针从前往后,right从后往前,直到二者相遇
		for (int l = i + 1, r = nums.size() - 1; l < r;){
			int t = nums[i] + nums[l] + nums[r];
			//当前和小于0,left右移动
			if (t < 0) ++l;
			else if (t > 0) --r;
			//如果满足条件,则加入列,且需要去重
			else {
				ans.push_back(vector<int>{nums[i], nums[l], nums[r]});
				++l;
				while (l < r && nums[l] == nums[l - 1]) ++l;
				--r;
				while (l < r && nums[r] == nums[r + 1]) --r;
			}
		}
	}
	return ans;
}

void test_threeSum(){
	vector<int> v1 = { -1, 0, 1, 2, -1, -4 };
	vector<vector<int>> ans = threeSum(v1);
	for (vector<vector<int>>::iterator it = ans.begin(); it < ans.end(); it++){
		for (vector<int>::iterator it1 = it->begin(); it1 < it->end(); it1++){
			cout << *it1 << " " ;
		}
		cout << endl;
	}
}

int main(){
	test_threeSum();
	getchar();
}

猜你喜欢

转载自blog.csdn.net/akenseren/article/details/80489866
今日推荐