給定一個(gè)包含 n 個(gè)整數(shù)的數(shù)組 nums部翘,判斷 nums 中是否存在三個(gè)元素 a,b响委,c 新思,使得 a + b + c = 0 ?找出所有滿足條件且不重復(fù)的三元組赘风。
注意:答案中不可以包含重復(fù)的三元組夹囚。
例如, 給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
想不到除了暴力更好的方法邀窃,于是參考了這篇博客《LeetCode 15. 三數(shù)之和(3Sum)》
首先對(duì)數(shù)組排序荸哟,然后依次遍歷數(shù)組元素。
第一個(gè)元素必須為負(fù)數(shù)或0瞬捕,這樣才可能三數(shù)相加為0鞍历。
然后對(duì)后續(xù)元素采用雙指針移動(dòng)的方法,不斷移動(dòng)肪虎,找出所有解劣砍。
但雙指針移動(dòng)的時(shí)候,可能會(huì)導(dǎo)致出現(xiàn)重復(fù)解扇救。我通過添加了一些while循環(huán)刑枝,每次剔重
這篇博客引用了一個(gè)新的變量,用來存儲(chǔ)上一次的第二個(gè)數(shù)字的大小爵政,如此一來只需要簡單判斷就可以完成仅讽。確實(shí)比較巧妙。
我的具體代碼:
#include<vector>
#include<ctype.h>
#include<stdio.h>
#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
//為了sort函數(shù)引入
using namespace std;
vector< vector<int> > threeSum(vector<int>& nums) {
vector<vector<int> > res;
if(nums.size() < 3){
return res;
}
vector<int> vec;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2;){
if(nums[i] <= 0){
int target = 0 - nums[i];
int left = i + 1;
int right = nums.size() - 1;
while(left < right){
cout << "left:" << left << " ri:" << right << endl;
if(nums[left] + nums[right] == target){
vec.push_back(nums[i]);
vec.push_back(nums[left]);
vec.push_back(nums[right]);
res.push_back(vec);
vec.pop_back();
vec.pop_back();
vec.pop_back();
cout << "yeah! 1:" << i << " 2:" << left << " 3:" << right << endl;
left++;
right--;
while(left < right && nums[left] == nums[left - 1]){
left++;
}
while(left < right && nums[right] == nums[right + 1]){
right--;
}
}
else if(nums[left] + nums[right] < target){
left++;
while(left < right && nums[left] == nums[left - 1]){
left++;
}
}
else{
right--;
while(left < right && nums[right] == nums[right + 1]){
right--;
}
}
}
}
i++;
while(i < nums.size() - 2 && nums[i] == nums[i-1]){
i++;
}
}
return res;
}
int main(){
int a[10] = {-1,0,1,2,-1,-4};
vector<int> nums(a,a+6);
vector<vector<int> > res = threeSum(nums);
return 0;
}