LeetCode-Two Sum II - Input array is sorted

这个就是array已经有序 就可以用两个pointer的方法了。

注意不要想成二分,这个是从两端逼近,每次只移动一个位置,整个array扫一遍。

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


你可能感兴趣的:(LeetCode-Two Sum II - Input array is sorted)