Given an array of integers, return indices of the two numbers such that they add up to a specific target.code
You may assume that each input would have exactly one solution.ci
Example:
Given nums = [2, 7, 11, 15], target = 9,get
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].input
創建hashmap,去查找餘數是否存在。hash
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; _map.clear(); int size = nums.size(); for (int i = 0; i < size; i++) { int cur = nums[i]; int need = target - cur; auto f = _map.find(need); if (f != _map.end()) { res.push_back(f->second + 1); res.push_back(i + 1); return res; } _map[cur] = i; } return res; } private: unordered_map<int, int> _map; };