Skip to content

Latest commit

 

History

History
32 lines (24 loc) · 773 Bytes

File metadata and controls

32 lines (24 loc) · 773 Bytes

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


思路:

跟第一题是一个思路。 不过用的时间更短了。 想清楚左边界和右边界的变化。


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