中級算法之數組和字符串:三數之和

給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。

注意:答案中不可以包含重複的三元組。

示例:

給定數組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合爲: [ [-1, 0, 1], [-1, -1, 2] ]

思路:首先進行排序,然後順序篩選i,作爲基數,再在i的後面的數中利用二分查找找到能讓三者之和等於0的另外兩個數。
關鍵點:爲了避免重複,我這裏採用了重複的i不再參與+set存儲來解決的。

vector<vector<int>> threeSum(vector<int>& nums) {
	vector<vector<int>> res;
	set<vector<int>> tres;
	if (nums.size() < 3) return res;
	sort(nums.begin(), nums.end());
	int pre = nums[0];
	for (int i = 0; i <= nums.size() - 3; i++) {
		if (i != 0 && pre == nums[i]) continue;//避免結果重複
		if (nums[i] > 0) break;
		int front = i + 1, tail = nums.size() - 1;
		while (front < tail) {
			if (nums[i] + nums[front] + nums[tail] == 0) {
				vector<int>temp;
				temp.push_back(nums[i]);
				temp.push_back(nums[front]);
				temp.push_back(nums[tail]);
				tres.insert(temp);//避免重複
				front++;
				tail--;
			}
			if (nums[i] + nums[front] + nums[tail] < 0) front++;
			if (nums[i] + nums[front] + nums[tail] > 0) tail--;
		}
		pre = nums[i];
	}
	res.assign(tres.begin(), tres.end());
	return res;
}
發佈了44 篇原創文章 · 獲贊 0 · 訪問量 1282
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章