leetcode-1. Two Sum

来源:互联网 发布:做网络销售工资怎么样 编辑:程序博客网 时间:2024/04/30 01:59

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路:遍历,存哈希表

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        //思路:遍历,找到就返回位置,未找到用hashmap存        map<int,int> myMap;        vector<int> result;        int toFindNum = 0;        for(int i = 0;i < nums.size();i++)        {            toFindNum = target - nums[i];            if(myMap.find(toFindNum) != myMap.end())            {                result.push_back(myMap[toFindNum]);                result.push_back(i);                return result;            }            myMap.insert(make_pair(nums[i],i));        }        return result;    }};
0 0