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
题目难度:Medium
解题思路:采用哈希表
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> mapping;
vector<int> result;
for(int i=0;i<nums.size();i++)
{
mapping[nums[i]]=i;
}
for(int i=0;i<nums.size();i++)
{
const int gap=target-nums[i];
if(mapping.find(gap)!=mapping.end()&&mapping[gap]>i)
{
result.push_back(i+1);
result.push_back(mapping[gap]+1);
}
}
return result;
}
};
本文介绍了一种解决两数之和问题的有效算法。通过使用哈希表存储数组中的元素及其索引,可以在O(n)的时间复杂度内找到两个数,使它们的和等于给定的目标值。该算法确保了每个输入都有唯一解,并返回这两个数的非零基索引。
349

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



