听说刷题是走向One Piece的宝藏的伟大航路,那么行くぞ!!!就从第一题开始吧!!!看看能走多远嘎嘎嘎。⭐🌟☀
题目描述
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.
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。假设每种输入只会对应一个答案。但是,不能重复利用这个数组中同样的元素。
举例
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解题思路
1希望遍历一次就可以找到数据的下标,即,通过target减去当前所在的数据就可以知道另一个数是否存在;
2通过预处理,得到一个哈希表,建立数和坐标之间的映射,哈希表是常数级的查找,所以遍历当下就可以查找另一个数是否存在
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;//定义一个hashmap
vector<int> res;//存放结果,就是数字下标
for (int i = 0;i<nums.size(); ++i)
{
m[nums[i]] = i;//直接在哈希中找就知道nums中的下标是什么了, 常数级的查找效率
}//成功创建哈希表
//开始查找,线性的一次查找
for (int i = 0; i<nums.size(); ++i)
{
int t = target - nums[i];
if(m.count(t)&& m[t]!=i)
{
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
};
小问题记录
在第一次提交的时候出错,获取数组长度用nums.length
了,与java混淆了,C++用sizeof(array)/sizeof(array[0])
获取一般数组长度,用.size()
获得动态数组的长度。