题目描述
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].
解题思路及代码示例
暴力破解法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> results;
for(int i=0; i<nums.size()-1; i++)
{
int tmp=0;
tmp = target - nums[i];
for(int j=i+1; j<nums.size(); j++)
{
if (tmp == nums[j])
{
results.push_back(i);
results.push_back(j);
}
}
}
return results;
}
};
时间开销:228 ms 内存开销:9.3 MB
哈希表法
/* 使用哈希表时,要包含头文件和对应name的命名空间声明
#include <unordered_map>
using std::unordered_map;
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for (int i=0; i<nums.size(); i++)
{
int tmp = target - nums[i];
//先查找当前的hash表,若存在目标元素,输出结果,若不存在,向hash表中插入新元素,再循环
if (hash.find(tmp) != hash.end()) //不等号成立时,找到目标元素
{
return vector<int> {hash[tmp], i};//hash[tmp]是查找到的元素下标,其值必小于i
}
else hash[nums[i]] = i;
}
return vector<int> {};//没查找到对应元素,返回空向量
}
};
时间开销:12 ms 内存开销:10.1 MB