您的位置:首页 > 其它

【leetcode】001 Two Sum

2015-01-30 21:53 399 查看
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

【题意解析】从numbers数组里面寻找两个数,使得其和等于target,要求这两个数的index从1开始编号且递增。题目仅有一组答案。

解题思路】第一反应是找出所有的配对,复杂度为O(n*n),这肯定不行。然后想到怎么样将时间复杂度减到O(n),每一个数我们肯定需要遍历一次。但对于配对时的找数的过程,我们可以利用hashmap的思想实现在O(1)时间确定是否存在我们需要找的数。

                  整个算法的过程为:遍历数组,对每一个遍历到的数若其对应的数hashmap中没有,则添加进hashmap;否则,证明我们已经找到两个数,结束程序。当我们遍历到的某一个数,其前面的数肯定已经在hashmap中。

                  注意:hashmap用stl中的unordered_map实现而非map,提高效率,因为我们不需要hashmap有序;利用unordered_map的count函数而非find函数使code更加简洁。

AC CODE:

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> vecres;
unordered_map<int, int> mapidx;
for (int i = 0; i < numbers.size(); ++i)
{
if (mapidx.count(target - numbers[i]))
{
vecres.push_back(mapidx[target - numbers[i]]);
vecres.push_back(i + 1);
break;
}
else
mapidx[numbers[i]] = i + 1;
}
return vecres;
}
};


题目链接:https://oj.leetcode.com/problems/two-sum/

leetcode全套习题code下载:

                               github:https://github.com/huoyao/TL_letcd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息