Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 167. Two Sum II - Input array is sorted (https://interviewrecipes.com/two-sum-ii) (https://youtu.be/i2y6LTIz_WU)
// Video Explanation: https://youtu.be/i2y6LTIz_WU
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
int left = 0; // Smallest number.
int right = n-1; // Largest number.
while (numbers[left] + numbers[right] != target) {
if (numbers[left] + numbers[right] < target) { // Current sum is not sufficient
// to reach the target.
left++; // Increase the smaller number.
} else { // Current sum exceeds the target.
right--; // Decrease the larger number.
}
}
return {left+1, right+1}; // Yay, solved.
}
};
// Time Complexity: O(n).
// Space Complexity: O(1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.