【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

理解,借鉴。

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