(leetcode题解)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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意是给定一个排好序的数组,找出两数之和等于target的位置。

既然知道其中一个数,找另一个数存不存在,我立刻想到用哈希表来实现查找比较快捷,找到之后定位就好了。C++实现如下:

vector<int> twoSum(vector<int>& numbers, int target) {
        unordered_map<int,int> hash_map;
        vector<int> res;
        for(auto &i:numbers)
            hash_map[i]++;
        int temp;
        int j=0;
        for(auto &i:numbers)
        {
            if(hash_map[target-i])
            {
                res.push_back(j+1);
                temp=target-i;
                break;
            }
            j++;
        }
        for(int i=j+1;i<numbers.size();i++)
            if(temp==numbers[i])
                res.push_back(i+1);
        return res;
}

 

参考网上,另一种解法我觉得也挺不错的,即用双指针,一个指向数组头,一个指向数组尾,通过移动两个指针在实现查找,因为数组本身是排好序的,所以这个是可以完美实现的。C++实现如下,以做参考:

vector<int> twoSum(vector<int>& numbers, int target) {
        int l = 0, r = numbers.size() - 1;
        while (l < r) {
            int sum = numbers[l] + numbers[r];
            if (sum == target) 
                return {l + 1, r + 1};
            else if (sum < target) 
                ++l;
            else 
                --r;
        }
        return {};
    }

 

转载于:https://www.cnblogs.com/kiplove/p/6986738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值