Algo: Two Sum

本文介绍了LeetCode上的经典问题“两数之和”的两种不同情况及其解决方案:一种是在无序数组中寻找两个数使它们的和等于特定目标值;另一种是在已排序数组中寻找这两个数。对于无序数组的问题,采用哈希表来提高查找效率;对于已排序数组,则使用双指针技巧。文章提供了完整的C++实现代码。

 

    类似的题目可以用HashTable的思想解决。

1、Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

https://leetcode.com/problems/two-sum/description/

http://www.cnblogs.com/grandyang/p/4130379.html

https://blog.youkuaiyun.com/gatieme/article/details/50596965

https://segmentfault.com/a/1190000006697526

 

#include <vector>
#include <unordered_map>


std::vector<int> twoSum(std::vector<int>& nums, int target)
{
    int size = (int)nums.size();
    
    std::unordered_map<int, int> mp;
    std::vector<int> ans;
    
    for(int i = 0; i < size; ++i)
    {
        if(mp.count(target - nums[i]))
        {
            ans.push_back(mp[target - nums[i]]);
            ans.push_back(i);
            
            break;
        }
        
        mp[nums[i]] = i;
    }
    
    return ans;
}

 

2、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.

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

https://www.cnblogs.com/grandyang/p/5185815.html

#include <vector>

std::vector<int> twoSum(std::vector<int>& numbers, int target)
{
    int l = 0;
    int r = (int)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 {};
}

 

3、

 

转载于:https://www.cnblogs.com/noryes/p/7884526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值