167. Two Sum II - Input array is sorted-----binary search

題目如下:

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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        int[] ans = new int[2];
        
        if(numbers==null||numbers.length<2) return ans;
        
        while(left<right){
            int sum = numbers[left]+numbers[right];
            if(sum==target){
                ans[0] = left+1;
                ans[1] = right+1;
                break;
            }else if(sum>target){
                right--;
            }else left++;
        }
        return ans;
    }
}
需要注意的:

1. numbers的原始判斷

2. sum的定義要在while循環裏面

3. ans的答案返回的是index,但是題目中的index是從1開始的,所以返回的時候要+1.

發佈了59 篇原創文章 · 獲贊 1 · 訪問量 9347
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章