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, A, target=9
Output:index1=1, index2=2
Tags: Array Hash Table
Solution 1:Time Limit exceeded
vector<int> Twosum (vector<int>& Nums,inttarget) {Vector<int>ret; if(Nums.empty ())returnret; for(intI=0; I<nums.size (); i++){ intx=target-Nums[i]; for(intj=i+1; J<nums.size (); j + +){ if(nums[j]==x) {Ret.push_back (i+1); Ret.push_back (J+1); Break; } } } returnret; }
Solution 2: map
vector<int> Twosum (vector<int>& Nums,inttarget) {Vector<int>ret; Map<int,int>m; for(intI=0; I<nums.size (); i++){ if(!M.count (Nums[i])) M.insert (Make_pair (nums[i], i)); if(M.find (target-nums[i])! =M.end ()) { if(i>m[target-Nums[i]]) {Ret.push_back (M[target-nums[i]]+1); Ret.push_back (i+1); Break; } } } returnret; }
"Leetcode" 1-two Sum