Link Search Menu Expand Document

167. Two Sum II - Input array is sorted

Solution Code

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int index1 = 0, index2 = numbers.size() - 1, sum;
        vector<int> answer;
        
        while(index1 < index2) {
            sum = numbers[index1] + numbers[index2];
            
            if(sum == target)
                break;
            else if(sum < target)
                index1++;
            else
                index2--;
        }
        
        answer.push_back(index1 + 1);
        answer.push_back(index2 + 1);
        
        return answer;
    }
};

© 2023. All rights reserved.

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy