問題
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.
輸入
Given nums = [2, 7, 11, 15], target = 9
輸出
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
分析
首先考慮枚舉兩個數(shù)字,復(fù)雜度為O(n^2)。
但是題目強(qiáng)調(diào)了只有一組解,這就意味著數(shù)組元素的值可以被用來當(dāng)做鍵值,即元素的值當(dāng)鍵,元素的下標(biāo)當(dāng)值,這樣就能通過值來快速查找下標(biāo)。我們用unordered_map作為關(guān)聯(lián)容器來存儲鍵值對,把查找的復(fù)雜度降至O(1)。
要點(diǎn)
- 把值當(dāng)鍵,下標(biāo)當(dāng)值,即倒排索引;
- unordered_map使用hash表作為底層數(shù)據(jù)結(jié)構(gòu),雖然不能像map一樣保持元素的順序,但是卻能把查找的復(fù)雜度降至O(1)(map的查找操作需要O(logn))。
時間復(fù)雜度
O(n)
空間復(fù)雜度
O(1)
代碼
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> umap; // 倒排索引表
for (int i = 0; i < nums.size(); i++) {
// 在map中查找有沒有元素的鍵等于目標(biāo)值減當(dāng)前值
// 如果沒有,就把當(dāng)前元素的值和下標(biāo)插入map中
// 如果有,就把當(dāng)前元素的下標(biāo)和找到的元素的下標(biāo)返回即可
if (umap.find(target - nums[i]) == umap.end()) {
umap[nums[i]] = i;
}
else {
res.push_back(i);
res.push_back(umap[target - nums[i]]);
}
}
return res;
}
};