Description
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].
Solution
简单实现,两层循环暴力搜索完成,时间复杂度为 O(n2) ,空间复杂度为 O(1) ,超时
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> indices;
for(int i = 0; i < nums.size()-1; i ++){
for(int j = i + 1; i < nums.size(); j++){
if(nums[i] + nums[j] == target){
indices.push_back(i);
indices.push_back(j);
}
}
}
return indices;
}
};
建立hash表以空间换时间,使用map结构完成
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> indices;
map<int, int> hash_m;
for(int i = 0; i < nums.size(); i ++){
hash_m[nums[i]] = i;
}
map<int, int>::iterator it;
for(int i = 0; i < nums.size(); i ++){
it = hash_m.find(target - nums[i]);
if(it != hash_m.end()){ // end()是指最后一个元素的后面
if(i == it->second) continue;
// it->first返回当前元素的关键字,it->second返回当前元素的值
indices.push_back(i);
indices.push_back(it->second);
return indices;
}
}
return indices;
}
};