LeetCode - 167. Two Sum II - Input array is sorted

链接

167. Two Sum II - Input array is sorted

题意

给定一个升序的整型数组,其中有两个元素的和为指定的数,找到这两个元素的下标。注意只有唯一解。

思路

利用双指针,从两端到中间扫描。

  1. 如果相加恰好为target,则直接返回。
  2. 如果相加小于target,说明左指针需要增加。
  3. 如果相加大于target,说明右指针需要减少。

代码

Java :

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

效率

Your runtime beats 48.01 % of java submissions.

posted @ 2017-04-27 13:22  zyoung  阅读(107)  评论(0编辑  收藏  举报