您的位置:首页 > 职场人生

leetcode之2sum

2016-03-03 18:44 555 查看
题目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input
would have exactly one solution.

解答:

直接用hash即可,在C++中就是map

一开始看错了,看成找这两个数了,如果是这样就直接排序,

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
int size = nums.size();
int left;
for (int i = 0; i < size; ++i)
{
left = target - nums[i];
auto itr = m.find(left);
if (itr != m.end())
return{ i, itr->second };
m[nums[i]] = i;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试