题目:
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
class Solution {
public:
//hash table
//STL的hash_map的find的时间复杂度是O(1);map的find是用红黑树实现的,时间复杂度是O(logn)
//leetcode不支持hash_map, 所以总的时间复杂度是O(nlogn)
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
if (nums.size() < 2) return res;
map<int, int> hashMap;
hashMap[nums[0]] = 0;//map可以直接使用下标操作,若建不存在,则插入key并初始化value然后用右值给value赋值。
for (int i = 1; i < nums.size(); ++i){
map<int, int>::iterator iter = hashMap.find(target - nums[i]);
if (iter != hashMap.end()) {
res.push_back(iter->second + 1);
res.push_back(i + 1);
return res;
}
hashMap[nums[i]] = i;
}
return res;
}
};