LeetCode筆記:167. 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. 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

大意:

給出一個遞增排好序的整型數組,找出兩個數組相加等于目標數字。
函數 twoSum 應該返回兩個數字的索引,index1 必須小于 index2。請注意你返回的結果(index1 和 index2)不是基于0開始的。
你可以假設每個輸入都有一個結果。
輸入:numbers={2, 7, 11, 15}, target=9
輸出:index1=1, index2=2

思路:

最直接的方法是遍歷每一個數,然后看它后面的每個數與它相加能不能等于目標數字,但是這樣太慢了。

要利用好數組已經排好序的條件,兩個數相加一定是一大一小相加得出目標數字,那么我們可以用兩個游標,一個從數組頭開始遍歷,一個從數組尾開始遍歷,如果數組頭的數字小于目標數字減去數組尾的數字,則數組頭的游標往后移動一格,否則數組尾的游標往前移動一格。如果兩個數字相加正好等于目標數字,那么結束循環將結果返回,注意索引要求從1開始,所以我們要將得出得的兩個索引號都加一。

舉個例子,數組為 [1,2,3,4],目標數字為6,i 和 j 分別一開始在1和4兩個數字,因為1小于6-4,所以數組頭的游標指向2,數組尾的游標不變,此時2+4正好等于6,返回結果索引為2和4,而不是1和3。

代碼(Java):

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        int i = 0;
        int j = numbers.length-1;
        while (i < j) {
            if (numbers[i] + numbers[j] == target) {
                result[0] = i+1;
                result[1] = j+1;
                break;
            }
            if (numbers[i] < target - numbers[j]) i++;
            else j--;
        }
        return result;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容