Given an array of integers, find two numbers that theirdifferenceequals to a target value.
where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.
Notice
It's guaranteed there is only one available solution
Have you met this question in a real interview?
Yes
Example
Given nums =[2, 7, 15, 24], target =5
return[1, 2](7 - 2 = 5)
class Solution {
public:
/*
* @param nums an array of Integer
* @param target an integer
* @return [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum7(vector<int> &nums, int target) {
// write your code here
unordered_map<int, int> hash;
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
int tmp = nums[i] + target;
if (hash.count(tmp)) {
res.push_back(hash[tmp] + 1);
res.push_back(i + 1);
break;
}
tmp = nums[i] - target;
if (hash.count(tmp)) {
res.push_back(hash[tmp] + 1);
res.push_back(i + 1);
break;
}
hash[nums[i]] = i;
}
return res;
}
};