clueless coding // TODO: be smarter

LeetCode Two Sum II - Input array is sorted: CPP Solution



TL;DR Code Solution


vector<int> twoSum(vector<int>& numbers, int target) {

    int left = 0;
    int right = (int)numbers.size() - 1;

    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) {
            vector<int> result = {left + 1, right + 1};
            return result;
        }
        else if (sum < target) {
            left++;
        }
        else {
            right--;
        }
    }

}