LeetCode笔记:167. Two Sum II - Input array is sorted

问题:

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. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

大意:

给出一个递增排好序的整型数组,找出两个数组相加等于目标数字。

函数 twoSum 应该返回两个数字的索引,index1 必须小于 index2。请注意你返回的结果(index1 和 index2)不是基于0开始的。

你可以假设每个输入都有一个结果。

输入:numbers={2, 7, 11, 15}, target=9
输出:index1=1, index2=2

思路:

最直接的方法是遍历每一个数,然后看它后面的每个数与它相加能不能等于目标数字,但是这样太慢了。

要利用好数组已经排好序的条件,两个数相加一定是一大一小相加得出目标数字,那么我们可以用两个游标,一个从数组头开始遍历,一个从数组尾开始遍历,如果数组头的数字小于目标数字减去数组尾的数字,则数组头的游标往后移动一格,否则数组尾的游标往前移动一格。如果两个数字相加正好等于目标数字,那么结束循环将结果返回,注意索引要求从1开始,所以我们要将得出得的两个索引号都加一。

举个例子,数组为 [1,2,3,4],目标数字为6,i 和 j 分别一开始在1和4两个数字,因为1小于6-4,所以数组头的游标指向2,数组尾的游标不变,此时2+4正好等于6,返回结果索引为2和4,而不是1和3。

代码(Java):

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        int i = 0;
        int j = numbers.length-1;
        while (i < j) {
            if (numbers[i] + numbers[j] == target) {
                result[0] = i+1;
                result[1] = j+1;
                break;
            }
            if (numbers[i] < target - numbers[j]) i++;
            else j--;
        }
        return result;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值