simple C++ O(n) solution


  • 1
    Q
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> r;
        vector<int>::iterator i1 = numbers.begin(), i2 = numbers.end() - 1;
        while (i1 != i2) {
            if (*i1 + *i2 == target) {
                r.push_back(i1 - numbers.begin() + 1);
                r.push_back(i2 - numbers.begin() + 1);
                break;
            }
            if (*i1 + *i2 < target) ++i1;
            else --i2;
        }
        return r;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.