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

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

其实和Two Sum一样,只不过给的数组是排好序的而已,且返回索引从1开始,所以我们提出下面三种解决方案:

  1. 双指针法
  2. map法
  3. binary search法

第一种方法,两个指针分别从0和length-1开始遍历,然后求和两个数,如果等于target就返回,如果大于则right–,否则left++。代码如下所示:

    public int[] twoSum(int[] numbers, int target) {
        int [] res = new int [2];
        int left = 0, right = numbers.length-1;
        while(left < right){
            int tmp = numbers[left] + numbers[right];
            if(tmp == target){
                res[0] = left + 1;
                res[1] = right + 1;
                break;
            }else if(tmp < target)
                left ++;
            else
                right --;
        }
        return res;
    }

另外一种方法就是使用map来保存遍历过的数组信息,与Two Sum原理相同。代码入下:

    public int[] twoSum1(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int [] res = new int[2];
        for(int i=0; i<numbers.length; i++){
            if(map.containsKey(numbers[i])){
                res[0] = map.get(numbers[i]);
                res[1] = i+1;
                break;
            }else
                map.put(target-numbers[i], i+1);
        }
        return res;
    }

方法三是使用binary search,其实跟方法一思路很相近,这里就不再进行赘述。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值