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.
Note:
- 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.
Example:
Input: numbers = [,,,], target =
Output: [,]
Explanation: The sum of and is . Therefore index1 = , index2 = .
题目描述,给定一个已排序的数组,和一个目标值,计算数组中的两个值的和等于目标值时的位置,这里位置不从0开始。
思路: 数组是以排序的,则使用两个指针,分别指向数组的头尾,当两数相加小于目标值是则头指针递增一位,当相加大于目标值值,尾指针递减。
下面是代码,感觉还有优化的地方。先贴出来。
public int[] TwoSum(int[] numbers, int target)
{
int[] result = new int[];
int lo=, hi=numbers.Length-;
while(lo < hi)
{
if (numbers[lo] + numbers[hi] < target) lo++;
else if (numbers[lo] + numbers[hi] > target) hi--;
else
break;
}
result[] = lo + ;
result[] = hi + ;
return result;
}