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 = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1
中文大意:
给定一个已按升序排序的整数数组,找到两个数字,使它们相加得到一个特定的目标数字。函数two和应该返回两个数字的指标,使它们相加得到目标值,其中index1必须小于index2。
注记:您返回的答案(index1和index2)不是基于零的。您可以假设每个输入都只有一个解决方案,并且可能不会两次使用相同的元素。
解题思路:
一个数组,取两个值相加得到target,由于这个数组它的顺序是有序的,所以分别去前面的值与后面的值进行相加,当得到result结果时,我们可以返回一个result数组值,即返回最后的结果
代码如下
class Solution {
public int[] twoSum(int[] numbers, int target) {
//最后的返回的数组,记录结果数组由那两个位置的值进行相加的到
int[] result=new int[2];
//前向的标记
int count1=0;
//后向的标记
int count2=numbers.length-1;
//依次遍历数组
while(count1<count2)
{
//得到result时,返回两个结果位置
if(numbers[count1]+numbers[count2]==target)
{
result[0]=count1+1;
result[1]=count2+1;
break;
}
//结果大于target时,将后面的count2向前移
else if(numbers[count1]+numbers[count2]>target)
{
count2--;
}
//结果小于target时,将前面的count1向后移
else{
count1++;
}
}
return result;
}
}