每日题解:LeetCode 167. 两数之和 II - 输入有序数组

Author Avatar
清水雅然君 07月 20,2020

题目地址

题目描述

解法

CPP

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
       int low = 0, high = numbers.size() - 1;
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target) {
                return {low + 1, high + 1};
            }
            if (sum < target) {
                ++low;
            }else{
                --high;
            }
        }
        return {-1, -1};
    }
}

JAVA

class Solution {
    public int[] twoSum(int[] numbers, int target) {
       Map<Integer,Integer> numMap=new HashMap();
            for(int i=0;i< numbers.length;i++){
             int difference=target-numbers[i];
             if(numMap.containsKey(difference)){
               return new int[]{numMap.get(difference)+1,i+1};
             }
             numMap.put(numbers[i],i);
         }
            return null;
    }
}

解题思路

hash表

思路与两数之和的解法一样,利hash表判断,目标值target与当前numbers[i]的差值,是否存在于hash表中,然后返两者的坐标值,这里稍微特殊处理一下,坐标值+1

   Map<Integer,Integer> numMap=new HashMap();
            for(int i=0;i< numbers.length;i++){
             int difference=target-numbers[i];
             if(numMap.containsKey(difference)){
               return new int[]{numMap.get(difference)+1,i+1};
             }
             numMap.put(numbers[i],i);
         }

双指针

由于题目已经说了数组为有序的,这样可以使用双指针解决,如果两个指针的和sum小于target,说明右边的值比较小,那就左指针往右移动,反之,说明右边值比较大
在这里插入图片描述
如图,双指针的和往右边是越来越大

 int low = 0, high = numbers.size() - 1;
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target) {
                return {low + 1, high + 1};
            }
            if (sum < target) {
                ++low;
            }else{
                --high;
            }
        }