Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2
Test instructions: Give you an array that tells you that the only solution is two numbers plus equals target, what are the subscripts?
Idea: Map discrete storage, a relatively simple problem
Class Solution {public: vector<int> twosum (vector<int> &numbers, int target) { Vector<int > ans; Map<int, Int> MP; for (int i = 0; i < numbers.size (); i++) { int tmp = target-numbers[i]; if (Mp.find (tmp)! = Mp.end ()) { ans.push_back (mp[tmp]); Ans.push_back (i+1); } else Mp[numbers[i]] = i+1; } return ans; };
Leetcode the Sum