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].
stupid的方法1:
//两遍遍历,确保检测所有的两数组合,相加得到target即返回两数下标.复杂度O(n^2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
vector<int> result;
for(int i = 0; i < n; i++){
for(int j = i+1; j < n;j++){
if((nums[i] + nums [j]) == target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
}
};
方法2:利用hashmap迅速查找
//第一遍遍历将向量nums中的元素按key为元素值,value为元素下标的方式写入map.
//第二遍遍历在map中找target-nums[i](逆向思维),用map自带的find()方法高效查找.若找到,则将两这个数的下标i和map[target-nums[i]]返回.复杂度O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hash;
vector<int> result;
for(int i = 0; i < nums.size(); i++){
hash[nums[i]] = i;
}
for(int i = 0; i < nums.size(); i++){
int num_to_find = target - nums[i];//要找的数
map<int, int>::const_iterator iter = hash.find(num_to_find);//用find()查找,返回的是map的迭代器
//若iter访问到end,说明没找到
if(iter != hash.end() && iter->second != i){//注意后一个条件不能省,不能找自身,比如4+4=8.
result.push_back(i);
result.push_back(iter->second);
return result;
}
}
}
};
方法3:一遍遍历,填充map的同时进行比对判断
//复杂度O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hash;
vector<int> result;
for(int i = 0; i < nums.size(); i++){
int num_to_find = target - nums[i];
map<int, int>::const_iterator iter = hash.find(num_to_find);
if(iter != hash.end()){
result.push_back(i);
result.push_back(iter->second);
return result;
}
hash[nums[i]] = i;
}
}
};