LeetCode167. Two Sum II
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Two Sum I中由于数组是无序的,使用了map来帮助查找,现在数组是有序的,就可以不用借助额外空间了。
从数组两端开始算他们的和,倘若比target大,就让右指针左移动来减少这个和,如果比target小的话,就让左指针右移动,来增加这个和。这样使得时间性能在O(N)中,而空间性能在O(1)中。