[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.

Note:

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: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

解法一

思路

这个是[leetcode]1.Two Sum的改编题,由于数组变成了有序,所以用二分法的思路来寻找target-numbers[i],这样的话时间复杂度为O(nlogn)。

代码

class Solution { 
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        for(int i=0; i<numbers.length-1; i++) {
            int start=i+1, end=numbers.length-1, gap=target-numbers[i];
            while(start <= end) {
                int m = (start+end)/2;
                if(numbers[m] == gap){
                    res[0] = i+1;
                    res[1] = m+1;
                    return res;
                }
                else if(numbers[m] > gap) end=m-1;
                else start=m+1;
            }
        }
        return res;
    }
}

解法二

思路

后来看到了一种更为精妙的方法,用两个指针分别指向数组的头和尾,如果指向的两个数刚好等于target,直接返回这两个位置即可,如果这两个数加起来大于target,那么右指针往左移一位,入果这两个数加起来小于target,那么左指针往右移动一位。时间复杂度为O(n)。

代码

class Solution { 
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        int i = 0;
        int j = numbers.length - 1;
        while(true){
            if(numbers[i] + numbers[j] == target) {
                res[0] = i+1;
                res[1] = j+1;
                break;
            }else if(numbers[i] + numbers[j] > target) j--;
            else i++;
        }
        return res;
    }
}
posted @ 2018-10-09 09:21  shinjia  阅读(110)  评论(0编辑  收藏  举报