Two Sum

来源:互联网 发布:守望先锋生涯数据 编辑:程序博客网 时间:2024/05/12 03:04


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

解题思路:用unordered_map,首先开始一个循环,如果没有找到元素与映射中的值相加等于target

(即find函数的返回值指向end()),就插入映射继续查找,否则查找成功。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int i;        vector<int> vint;        unordered_map<int,int> unmap;        unordered_map<int,int>::iterator iter;        for(i = 0;i <nums.size();++i)        {            if(( iter=unmap.find(target - nums[i])) == unmap.end())            unmap.insert(make_pair(nums[i],i));            else            {                vint.push_back(iter->second + 1);                vint.push_back(i+1);                break;            }        }        return vint;    }};



0 0