solution.cpp 729 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1
#include <unordered_map>
每日一练社区's avatar
每日一练社区 已提交
2 3 4
#include <vector>
#include <iostream>
using namespace std;
每日一练社区's avatar
每日一练社区 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
class Solution
{
public:
	vector<int> twoSum(vector<int> &nums, int target)
	{
		std::unordered_map<int, int> hset;
		vector<int> r;
		for (int i = 0; i < nums.size(); ++i)
		{
			int c = target - nums[i];
			auto iter = hset.find(c);
			if (iter != hset.end() && iter->second != i)
			{
				r.push_back(i);
				r.push_back(iter->second);
				return r;
			}
			hset.insert(std::make_pair(nums[i], i));
		}
		return r;
	}
每日一练社区's avatar
每日一练社区 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
};

int main()
{
	Solution test;
	int arr[] = {3, 2, 4};
	vector<int> ret;
	vector<int> vec(arr, arr + 4);
	ret = test.twoSum(vec, 6);
	for (auto i = ret.begin(); i != ret.end(); i++)
	{
		cout << *i << ' ';
	}
	return 0;
}