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].
解題思路
最直觀的想法采用暴力搜索法,時(shí)間復(fù)雜度為O(N*N), 但提交的時(shí)候Time Limit Exceeded, 因此暴力搜索不可取。
要想達(dá)到O(N)的時(shí)間復(fù)雜度,根據(jù)空間換時(shí)間的準(zhǔn)則,用哈希表存儲(chǔ)數(shù)組元素和Index的對(duì)應(yīng)關(guān)系,具體代碼如下:
class Solution
{
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
int temp = target - nums[i];
if (hash.find(temp) != hash.end()) { //如果在哈希表中查到對(duì)應(yīng)的數(shù)字,返回結(jié)果
res.push_back(hash[temp]);
res.push_back(i);
return res;
}
hash[nums[i]] = i; //沒有查到結(jié)果,將數(shù)組元素和Index加入哈希表
}
return res;
}
}