167. Two Sum II - Input array is sorted

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请注意,您返回的答案(index1index2)不是基于零的。

    您可以假设每个输入只有一个解决方案,您不能使用相同的元素两次。

    输入:numbers = {271115}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;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值