Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode/algorithms/cpp/3Sum/3Sum.cpp #96

Closed
zhangjiefeng opened this issue Feb 19, 2016 · 2 comments
Closed

leetcode/algorithms/cpp/3Sum/3Sum.cpp #96

zhangjiefeng opened this issue Feb 19, 2016 · 2 comments

Comments

@zhangjiefeng
Copy link

vector<vector > threeSum(vector &num) {

vector< vector<int> > result;

//sort the array, this is the key
sort(num.begin(), num.end());

int n = num.size();

for (int i=0; i<n-2; i++) {
    //skip the duplication
    if (i>0 && num[i-1]==num[i]) continue;
    int a = num[i];
    int low = i+1;
    int high = n-1;
    while ( low < high ) {
        int b = num[low];
        int c = num[high];
        if (a+b+c == 0) {
            //got the soultion
            vector<int> v;
            v.push_back(a);
            v.push_back(b);
            v.push_back(c);
            result.push_back(v);
            // Continue search for all triplet combinations summing to zero.
            //skip the duplication
            while(low<n && num[low]==num[low+1]) low++; 
            while(high>0 && num[high]==num[high-1]) high--; 
            low++;
            high--;
        } else if (a+b+c > 0) {
            //skip the duplication
            while(high>0 && num[high]==num[high-1]) high--;
            high--;
        } else{
            //skip the duplication
            while(low<n && num[low]==num[low+1]) low++;
            low++;
        } 
    }
}
return result;

}

The below line code may have problem,
"while(low<n && num[low]==num[low+1]) low++; "
Why not "while(low<n -1 && num[low]==num[low+1]) low++; "

@minhlongdo
Copy link

The fix you proposed would work.
The current code would break on [1,-1,-1,0].

@haoel
Copy link
Owner

haoel commented Feb 29, 2016

You are right! I will fix it

@haoel haoel closed this as completed in 23801d8 Feb 29, 2016
haoel added a commit that referenced this issue Nov 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants