問題
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ù)字,復雜度為O(n^2)。
但是題目強調了只有一組解,這就意味著數(shù)組元素的值可以被用來當做鍵值,即元素的值當鍵,元素的下標當值,這樣就能通過值來快速查找下標。我們用unordered_map作為關聯(lián)容器來存儲鍵值對,把查找的復雜度降至O(1)。
要點
- 把值當鍵,下標當值,即倒排索引;
- unordered_map使用hash表作為底層數(shù)據結構,雖然不能像map一樣保持元素的順序,但是卻能把查找的復雜度降至O(1)(map的查找操作需要O(logn))。
時間復雜度
O(n)
空間復雜度
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中查找有沒有元素的鍵等于目標值減當前值
// 如果沒有,就把當前元素的值和下標插入map中
// 如果有,就把當前元素的下標和找到的元素的下標返回即可
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;
}
};