Two Sum II - Input array is sorted

来源:互联网 发布:zygote启动优化 编辑:程序博客网 时间:2024/05/21 11:09

https://oj.leetcode.com/problems/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

 public int[] twoSum(int[] numbers, int target)


这一题在最初的two sum就讲过了。如果是一个排好序的数组,就头尾向中间聚集就好了。如果和比target大,就尾指针往前移,如果比target小就头指针往后移。这种题目已经出的太烂了,现在的面试过程中遇到的可能性已经很小了。就给出代码如下:

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


0 0
原创粉丝点击