Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Use hash table to save all the numbers. The pre-processing takes O(n), go through all the number is another O(n).
Using "unordered_map",
use [ ] to add (and update) value, or use insert(make_pair(key, value) instead.
use find(key) to search hash, in this case, because all the values must be greater than 0 (i + 1, i starts from 0), so use [ ] is a more cleaner way, by using [ ], if the key is no exist, it will return 0.
need to check the new index is not equal to the search index.
<span style="font-size:14px;">class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> cache;
vector<int> res;
for (int i = 0; i < numbers.size(); i ++) {
cache[numbers[i]] = i + 1;
}
for (int i = 0; i < numbers.size(); i ++) {
int index = cache[target - numbers[i]];
if (index > 0 && index != (i + 1)) {
res.push_back(i + 1);
res.push_back(index);
break;
}
}
return res;
}
};</span>
This approach passes all the test, but there is a potential bug. Consider case [0, 2, 3, 0], 0, cache[0] gives us "4", which is the second value of the key "0", if interviewee want larger index display first, then the bug will be critical. A cleaner and neat approach is here:
<span style="font-size:14px;">class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> cache;
vector<int> res;
for (int i = 0; i < numbers.size(); i ++) {
int val = target - numbers[i];
if (cache[val] > 0) {
res.push_back(cache[val]);
res.push_back(i + 1);
break;
}
cache[numbers[i]] = i + 1;
}
return res;
}
};</span>
What if there are more than one solution? Consider case [0, 0, 0], 0, the output shall be [[1,2],[1,3],[2,3]].
<span style="font-size:14px;">class Solution {
public:
void twoSum(vector<int> &numbers, int target) {
unordered_map<int, vector<int>> indexCache;
for (int i = 0; i < numbers.size(); i ++) {
unordered_map<int, vector<int>>::iterator iter = indexCache.find(numbers[i]);
if (iter != indexCache.end()) {
iter->second.push_back(i + 1);
} else {
indexCache[numbers[i]] = vector<int> (i + 1);
}
}
for (int i = 0; i < numbers.size(); i ++) {
int val = target - numbers[i];
if (indexCache.find(val) != indexCache.end()) {
for(int j = 0; j < indexCache[val].size(); j ++) {
int index = indexCache[val][j];
if (index > (i + 1)) {
cout << (i + 1) << " " << index;
}
}
}
}
}
};</span>