Last active
September 13, 2020 14:14
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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