two-sum

来源:互联网 发布:mahout java实例教程 编辑:程序博客网 时间:2024/04/24 01:45

题目描述

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

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> res;        unordered_map<int,int> my_map;        int bef;        int aft;        my_map[numbers[0]]=0;        for(int i=1;i!=numbers.size();++i)            {            if(my_map.find(target-numbers[i])!=my_map.end())                {                bef=my_map[target-numbers[i]];                aft=i;            }            else                my_map[numbers[i]]=i;        }        res.push_back(bef+1);        res.push_back(aft+1);        return res;    }};
0 0
原创粉丝点击