Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Last active September 13, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/c87849a152c7321031d89f99b96e9b89 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/c87849a152c7321031d89f99b96e9b89 to your computer and use it in GitHub Desktop.
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