滑動窗口-leetcode-167-倆樹之和

以長度爲 2 的整數數組 [index1, index2] 的形式返回這兩個整數的下標 index1 和 index2。

你可以假設每個輸入 只對應唯一的答案 ,而且你 不可以 重複使用相同的元素。

你所設計的解決方案必須只使用常量級的額外空間。

示例 1:

輸入:numbers = [2,7,11,15], target = 9
輸出:[1,2]
解釋:2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
示例 2:

輸入:numbers = [2,3,4], target = 6
輸出:[1,3]
解釋:2 與 4 之和等於目標數 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。
示例 3:

輸入:numbers = [-1,0], target = -1
輸出:[1,2]
解釋:-1 與 0 之和等於目標數 -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
提示:

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers 按 非遞減順序 排列
-1000 <= target <= 1000
僅存在一個有效答案

思路:滑動窗口


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        while(left<right){
            int res = numbers[left]+numbers[right];
            if(res==target){
                return new int[]{++left,++right};
            } else if (res > target) {
                right--;
            }else{
                left++;
            }
        }
        return new int[]{-1,-1};
    }
}
//leetcode submit region end(Prohibit modification and deletion)

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