Q167. Two Sum II
Last updated
Was this helpful?
Last updated
Was this helpful?
直达:
Given an array of integers that is alreadysorted 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 haveexactlyone solution and you may not use thesameelement twice.
Input:numbers={2, 7, 11, 15}, target=9 Output:index1=1, index2=2
使用两个指针,一个从左向右查找,一个从右向左查找,不同于O(n)方法的每次移动一个值。可以采用二分查找更新到最近的那个值。这样复杂度便是O(logn).