LeetCode
1 TwoSum
题目
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解答
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> rlt;
map<int, int> s;
for (int i = 0; i < nums.size(); i++)
{
map<int, int>::iterator it = s.find(nums[i]);
if (it == s.end())
s[target - nums[i]] = i;
else
{
rlt.push_back(it->second + 1);
rlt.push_back(i + 1);
return rlt;
}
}
}
};

此博客介绍了LeetCode上关于寻找数组中两个数之和等于特定目标数的问题的解决方案,包括使用哈希表实现的高效算法。
865

被折叠的 条评论
为什么被折叠?



