【LeetCode】Two Sum II - Input array is sorted(兩數之和 II - 輸入有序數組)

這道題是LeetCode裏的第167道題。

題目描述:

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

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

說明:

  • 返回的下標值(index1 和 index2)不是從零開始的。
  • 你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素。

示例:

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

兩邊向中間縮進,逐步判斷。

解題代碼:

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

提交結果:

個人總結:

剛開始還在猶豫是否需要使用哈希表做題,看到提示 tag 猶如醍醐灌頂,一點就通。

二分查找 + Map:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        int mid = left + ((right - left) >>> 1);
        while (left < right){
            // 小於說明還要二分
            if (target < numbers[mid]){
                right = mid;
                mid = left + ((right - left) >>> 1);
            } else {
                // 大於就開始遍歷
                // key = t - 當前數字  value = 下標
                Map<Integer, Integer> map = new HashMap<>();
                for (int i = left; i <= right; i++) {
                    // 如果匹配,返回
                    if (map.containsKey(target - numbers[i])){
                        return new int[]{map.get(target - numbers[i])+1, i+1};
                    } else {
                        map.put(numbers[i],i);
                    }
                }
            }
        }
        return null;
    }
}

Python 哈希表:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        data = {}
        for i in range(len(numbers)):
            n = target - numbers[i]
            if n in data:
                return [data[n],i+1]
            data[numbers[i]] = i+1

理解,借鑑。

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