题目:给定一个整数数组 nums 和一个整数目标值 target,在该数组中找出和为目标值 target 的那 两个整数,并返回它们的数组下标。可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。可以按任意顺序返回答案。
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
方法一:哈希表
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it -> second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
复杂度分析
时间复杂度:O(N)
空间复杂度:O(N)