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
Problem Solving Ideas:
(1) Violence
O (n^2) runtime O (1) space
Loop through each element x and the find if there is another value, the Equals to target–x.
(2) Hash
O (1) runtime O (n) space
Using a hash map, maps a value to its index.
Code
Class Solution {public: vector<int> twosum (vector<int>& nums, int target) { int i, sum; vector<int> results; Map<int, int> Hmap; for (i=0; I<nums.size (); i++) { if (!hmap.count (Nums[i])) { Hmap.insert (pair<int, int> (Nums[i], i)); } if (Hmap.count (Target-nums[i])) { int n=hmap[target-nums[i]]; if (n<i) { results.push_back (n+1); Results.push_back (i+1);
return results;}} } return results;} ;
Leetcode the Sum