167. Two Sum II - Input array is sorted(雙向指針)

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.

(給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。

函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2

Note:

  • Your returned answers (both index1 and index2) are not zero-based. (返回的下標值(index1 和 index2)不是從零開始的)
  • You may assume that each input would have exactly one solution and you may not use the same element twice.(你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素)

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

【分析】

這道題與上一題的不同在於本題中數組是升序的,所以我們可以採用雙向指針來解決。

左指針left從index = 0處開始向右移動,右指針right從最右端即array.length - 1處開始向左移動。

如果left所在位置的值+right位置所在的值恰好等於target,那麼就返回new int[] {left + 1, right + 1} (因爲題目中索引不是從0開始,而是從1開始)。

如果left所在位置的值+right位置所在的值大於target,右指針就需要向左移動一位;反之左指針需要向右移動一位,直到左右之和等於target。

Java實現代碼如下:

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

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章