您的位置:首页 > 编程语言 > C语言/C++

leetcode c++ 3sum

2014-11-05 23:37 411 查看
this problem is so easy that we just need i,j,k these 3 pointers.

when i is fixed that if we want get the precise value, we just need to move the pointer j and the pointer k.

1.But as we all know, that we don't need the duplicate answer.

when the array is sorted, we can judge whether num[j]equals num[j-1] and the same to k.

2.when we find a solution on a stable i,we should't stop looking for, So use break will lost some proper solution.so we just let j++ork--class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(),num.end());
vector<vector<int>> answer;
if(num.size()<3)
return answer;
//there is a bad situation. 0 0 0 0;when a[i]is the same as a[i+1] we can just continue
for(int i = 0;i<num.size()-2;i++)
{
if(num[i] == num[i-1]&&i>0)
continue;
int j = i+1;
int k = num.size()-1;
while(j<k)
{
//we must have the different j and different k and differen i
if(num[j] == num[j-1] && j-1>i)
{j++;continue;}
if(num[k] == num[k+1] && k+1<num.size()-1)
{k--;continue;}
if(num[j]+num[k] < -num[i])
{ j++; continue;}
if(num[j]+num[k] > -num[i])
{k--; continue;}
if(num[j]+num[k] == -num[i])
{
vector<int> temp;
temp.push_back(num[i]);
temp.push_back(num[j]);
temp.push_back(num[k]);
answer.push_back(temp);
// break; we can't break here,because there might be more than one vector when i is fixed
j++;
}
}

}
return answer;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: