LeetCode 之 Two Sum — C++ 实现

Two Sum

Given an array of integers, 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.

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

给定一个整型数组,找出和为给定目标值的两个数。

函数返回这两个数的索引,index1 必须小于 index2。注意,返回的索引不是从 0 开始的。

假设对于每个输入只有一个解。

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

分析

    使用 map,键为数组值,值为数组索引。用target减去数组值,然后在 map 中查找这个差值,如果存在,则返回两个索引;不存在,将此数组值存入 map 中,重复此过程指导查找完数组为止。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        if(nums.empty())//空
        {
            return vector<int>();
        }
        
        map<int, int> addend;
        int numsSize = nums.size();
        for(int index = 0; index < numsSize; ++index)
        {
            if(addend.find(target - nums[index]) == addend.end())//另一个加数不在 map 中,加入 map
            {
                addend[nums[index]] = index + 1;
            }
            else //找到两个合法的数
            {
                vector<int> ret;
                ret.push_back(addend[target - nums[index]]);
                ret.push_back(index + 1);
                
                return ret;
            }
        }
        
        return vector<int>();
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值