您的位置:首页 > 其它

leetcode -- Two Sum

2014-08-13 14:07 344 查看

文能深情寻萝莉,武能仗义护人妻

[问题描述]

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

[解题思路]

时间复杂度O(n), 空间复杂度O(n)

首先:使用map记录已经出现的数字。map(number, index)

然后:对新的数字x,就判断 target - x是否已经出现。出现则返回结果

std::vector<int> Solution::twoSum(std::vector<int> &numbers, int target)
{
std::map<int, int> kp;
int index1, index2, index=0;
for (std::vector<int>::iterator ite = numbers.begin(); ite != numbers.end(); ite ++){
index ++;
if (kp.find(target - *ite) != kp.end()){
index2 = index;
index1 = kp[target - *ite];
break;
}
else if(kp.find(*ite) == kp.end()){
kp[*ite] = index;
}
}
std::vector<int> ans;
ans.push_back(index1);
ans.push_back(index2);
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: