/*
* @lc app=leetcode.cn id=1 lang=cpp
*
* [1] 两数之和
*/
// @lc code=start
class Solution {
/*
思路:
先检查第二个数是否已记录,记录直接返回第二个数下表和当前数下表
未记录,则使用无序哈希表记录当前数字出现的下表索引
*/
public:
// 采用无序哈希表
unordered_map<int, int> um;
vector<int> twoSum(vector<int>& nums, int target)
{
for (int i=0; i<nums.size(); ++i) {
int anotherNum = target - nums[i];
if ( um.count(anotherNum) ) {
// 另一个数已记录,则直接返回另一个数的位置和当前数的位置
return vector<int> {um[anotherNum], i};
} else {
// 记录当前数的位置
um[nums[i]] = i;
}
}
return vector<int>();
}
};
// @lc code=end
leetcode 1.两数之和
最新推荐文章于 2024-07-23 16:17:06 发布