标签:
题目:给一个数组和一个目标数,判断数组中是否有两个数之和等于目标数,如果存在就返回这两个元素的下标。
思路:遍历一遍数组,存下目标数和数组元素之差;利用hash查找是否存在这个差,如果存在就返回数组元素的下标,否则就插入hashtable;如果遍历完成还没有找到就返回空的vector。
代码如下:
vector<int> twoSum(vector<int> &numbers, int target) {
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] + 1);
result.push_back(i + 1);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
标签:
原文地址:http://blog.csdn.net/sai1989825/article/details/46399065