LeetCode-167:Two Sum II - Input array is sorted (固定和的元素的索引 II)

Question

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 and you may not use the same element twice.

Example

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

问题解析:

给定升序排序数组,找到两个和为给定数字的元素,返回二者位置。注意index1 < index2,且不使用重复元素。

Answer

Solution 1:

左右两指针相加靠近。

  • 注意题目与LeetCode-1:Two Sum存在不同的地方,本题要求index1 < index2,可以使用除与LeetCode-1相同的HashMap之外其他的方法。
  • 题中要求index1 < index2,那么我们可以利用这样的性质,设置左右两个指针,从两端向中间逼近,每次都用两个数判断是否等于目标值,等于则返回,不等则判断大小,增减左右指针。
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        while (numbers[left] + numbers[right] != target){
            if (numbers[left] + numbers[right] > target){
                right--;
            }else{
                left++;
            }
        }

        return new int[]{left+1, right+1};
    }
}
  • 时间复杂度:O(n);空间复杂度:O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值