Given an array of integersthat is already sorted in ascending order, find two numbers such that they addup to a specific target number.
The function twoSum shouldreturn indices of the two numbers such that they add up to the target, whereindex1 must be less than index2. Please note that your returned answers (bothindex1 and index2) are not zero-based.
You may assume that each inputwould have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15},target=9
Output: [1,2]
谷歌翻译:给定已经按升序排序的整数数组,找到两个数字,使得它们加起来达到特定的目标数。函数twoSum应该返回两个数字的索引,使得它们加到目标,其中index1必须小于index2。请注意,您返回的答案(index1和index2)不是基于零的。
您可以假设每个输入只有一个解决方案,您不能使用相同的元素两次。
输入:numbers = {2,7,11,15},target = 9 输出:[1,2]
我把他的输出改了一下,刚开始我还以为变成字符串输出。这题和刚开始想和求解Two Sum一样用map集合,最终测试没通过,发现可能会出现一样的数字。又改了一下,没考虑时间复杂度,用数组了遍历。因为他的数组是排好序的,所以直接在左右两边各放置一个计数器,然后看是否相等。代码如下:
public class Solution {
public int[] twoSum(int[] numbers, inttarget) {
int i=0,j=numbers.length-1;
int[] a=new int[2];
while(i<j){
if(numbers[i]+numbers[j]==target){
a[0]=i+1;
a[1]=j+1;break;
}
if(numbers[i]+numbers[j]>target)
j--;
if(numbers[i]+numbers[j]<target)
i++;
}
return a;
}
}