Leetcode 3Sum, leetcode3sum

Source: Internet
Author: User

Leetcode 3Sum, leetcode3sum

We assume that the three numbers of indexes are a, B, and c.

Duplicate production may occur in the following situations:

1. The first number leads to repetition, num [a] = num [A-1], followed by the same combination of B, c will lead to repeated answers

2. Repeat results from the second and third numbers only after an answer is found. Therefore, you only need to confirm that B ++, c -- is a different number.


    vector<vector<int>> threeSum(vector<int> &num) {        int b, c, n = num.size();        vector<vector<int>> result;        sort(num.begin(), num.end());        for(int i = 0; i < n-2; i++){            if(i > 0 && num[i] == num[i-1])                continue;            b = i+1;            c = n-1;            while(b < c){                if(num[i] + num[b] + num[c] < 0)                    b++;                else if(num[i] + num[b] + num[c] > 0)                    c--;                else {                    vector<int> tmp;                    tmp.push_back(num[i]);                    tmp.push_back(num[b]);                    tmp.push_back(num[c]);                    result.push_back(tmp);                    b++;c--;                    while(num[b] == num[b-1])           // avoid duplicates                        b++;                    while(num[c] == num[c+1])                        c--;                }            }        }        return result;    }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.