给定一个数组nums,一个目标值target,在数组找两个数满足这两个数的和为target。
返回这两个数在nums中的下标。
example:
nums = [2,7,11,15]
target = 9
return [0,1]
题意分析:
在数组中寻找两个数a,b,使得a+b = target,返回a,b的下标
思路分析:
这是一道经典的在数组中找和为定值的题目。通常这种题目有以下几种解法:
- 将数组进行双层遍历,直到找到第一层的数和第二层的数相加等于目标数
- 将遍历过的数a全部记录下来,然后对正在遍历的数b进行判断,判断target - b是否已经遍历过。(time: O(n), space: O(n))
对于思路一:
'''
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//unordered_map<int,int> hash;//用于存储访问过的值和索引
vector<int> ans;
int i,j;
for(i=0;i<nums.size();i++){
for(j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
}
return ans;
}
};
15:24:07
CA 2018/10/10 15:24:07
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
int i;
for(i=0;i<nums.size();i++){
int dest_num=target-nums[i];
if(hash.find(dest_num)!=hash.end()){
ans.push_back(hash.find(dest_num));
ans.push_back(i);
return ans;
}
hash[nums[i]]=i;
}
return ans;
}
};
'''
结果:
对于思路二:
'''
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//unordered_map<int,int> hash;//用于存储访问过的值和索引
vector<int> ans;
int i;
for(i=0;i<nums.size();i++){
int dest_num=target-nums[i];
if(hash.find(dest_num)!=hash.end()){
ans.push_back(hash.find(dest_num));
ans.push_back(i);
return ans;
}
hash[nums[i]]=i;
}
return ans;
}
};
'''
结果:
关于unordered_map解释:
unordered_map 是一种关联容器,用于存储由关键值 (Key Value,以下称为Key 值) 和映射值 (Mapped Value,以下称为映射值) 组成的元素,并且允许根据其 Key 值快速检索各个元素。
在 unordered_map 容器中,Key 值通常用来唯一标识元素,映射值是与该 Key 值关联内容的对象。Key 值与映射值的类型可能不同。
在 unordered_map 内部,元素没有按照其 Key 值与映射值的任何顺序进行排序 ,而是根据它们的 Hash 值组织成桶,允许它们通过其 Key 值直接快速访问单个元素(通常具有常数等级的平均时间复杂度)。
unordered_map 容器与 map 容器相比,通过 Key 值访问各个元素的速度更快,然而通过其元素子集进行范围迭代的效率通常较低。
unordered_map 实现了直接访问操作符 (operator[]),它允许使用 Key 值作为输入参数,直接访问映射值。
部分操作函数基本和 map 相同:
- clear
-
- 清除 map 中所有元素;
- erase
-
- 删除 map 中指定位置的元素;
- insert
-
- 在 map 指定位置添加 pair 类型的元素;
- find
-
- 获取 map 中元素的迭代器;
- begin, end
-
- map 的正向迭代器的起始位置与终点位置;