您的位置:首页 > 其它

leetcode-1.two sum

2018-01-27 17:56 363 查看
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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


思路:找容器vector中找到两个数使得A+B=Target,可以建立无序容器unordered_map,在unordered_map依次查找vector中的每个元素i,若没有找到,则在unordered_map中建立key为Target-i ,value为i的index的元素,直到在unordered_map找到i。

#include <vector>
#include<iostream>
#include <unordered_map>
using namespace std;

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> record;
for (int i = 0; i != nums.size(); ++i) {
auto found = record.find(nums[i]);
if (found != record.end())
return { found->second, i };
record.emplace(target - nums[i], i);
}
return { -1, -1 };
}
};

int main()
{
vector<int> vec = { 1, 4 ,6 ,7, 8, 13 };
int tar = 12;
Solution solu;
vector<int>  p=solu.twoSum(vec, tar);
for (auto &num : p)
cout << num << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: