题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].题目没什么,主要是一句话:不能用同一个元素两次。换句话说不能把原数组循环两次。但它又没说是O(n),那可以说,我存在其他地方这个元素也只用了一次呀。。但这个题的本身目的肯定是让写O(n)的代码的。也很简单,用map。过一个元素,存进map一个值。然后过下一个元素看看map里有没有想要的值。有就返回这俩的下表。贴代码。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int, int> hash;
int flag = 0;
for(int i = 0; i < nums.size(); i++){
if(hash.find(target - nums[i]) != hash.end()){
result.push_back(hash[target - nums[i]]);
result.push_back(i);
break;
}
hash[nums[i]] = i;
}
return result;
}
};
嗯~