Description
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:
Example:
- 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: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
題目描述,給定一個已排序的數組,和一個目标值,計算數組中的兩個值的和等于目标值時的位置,這裡位置不從0開始。
思路: 數組是以排序的,則使用兩個指針,分别指向數組的頭尾,當兩數相加小于目标值是則頭指針遞增一位,當相加大于目标值值,尾指針遞減。
下面是代碼,感覺還有優化的地方。先貼出來。
public int[] TwoSum(int[] numbers, int target)
{
int[] result = new int[2];
int lo=0, hi=numbers.Length-1;
while(lo < hi)
{
if (numbers[lo] + numbers[hi] < target) lo++;
else if (numbers[lo] + numbers[hi] > target) hi--;
else
break;
}
result[0] = lo + 1;
result[1] = hi + 1;
return result;
}

轉載于:https://www.cnblogs.com/c-supreme/p/9559971.html