LeetCode 之 Two Sum — C++ 实现

来源:互联网 发布:centos没有桌面 编辑:程序博客网 时间:2024/06/05 06:05

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