C++ two pointer O(n) time O(1) space easy to understand


  • 0
    J
    class Solution {
    public:
        vector<int> twoSum(vector<int>& numbers, int target) {
            int len=numbers.size();
            int i=0;
            int j=len-1;
            while(i<j)
            {
                int sum=numbers[i]+numbers[j];
                if(sum==target)
                    return {i+1, j+1};
                else if(sum<target)
                    ++i;
                else if(sum>target)
                    --j;
            }
            return {};
        }
    };
    

Log in to reply
 

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