1. 程式人生 > >Given an array of integers that is already sorted in ascending order, find two numbers such that the

Given an array of integers that is already sorted in ascending order, find two numbers such that the

這道題自己思路也對了,就是陣列使用出了點問題,然後就是看了別人的程式碼才改過來,用到匿名陣列。

不多說,看程式碼,

 

class Solution {
    public int[] twoSum(int[] numbers, int target) {
    if(numbers==null || numbers.length < 1) return null;
        int i=0, j=numbers.length-1;
        
        while(i<j) {
            int x = numbers[i] + numbers[j];
            if(x<target) {//如果和小於目標值,這說明要往左邊移,因為是升序陣列,反之也一樣
                ++i;
            } else if(x>target) {
                --j;
            } else {
                return new int[]{i+1, j+1};
            }
        }
        return null;

    }
}