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].
// two_sum.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
//#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS 1
//#include <hash_map>
#include <unordered_map>
#include <algorithm>
using namespace std;
/*****暴力搜索********/
class Solution_1 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>::iterator it = nums.begin();
vector<int>::iterator its;
vector<int> result;
for (;it < nums.end();it++)
{
for (its = it + 1;its < nums.end();its++)
{
if (*its == target - *it)
{
result.push_back(it - nums.begin());
result.push_back(its- nums.begin());
return result;
}
}
}
result.push_back(0);
result.push_back(0);
return result;
}
};
/*******Two-pass Hash Table******/
class Solution_2 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>::iterator it = nums.begin();
vector<int> result;
unordered_map<int, int> hash;
unordered_map<int, int>::iterator its=hash.begin();
int comp;
for (;it < nums.end();it++)
{
hash[*it] =it - nums.begin(); //hash表赋值
}
for (it = nums.begin();it < nums.end();it++)
{
comp = target - *it;
its = hash.find(comp); //搜索的是hash[k,v]的k
int k=it - nums.begin();
if (its != hash.end() && its->second!=k )
{
result.push_back(it - nums.begin());
result.push_back(its ->second);
return result;
}
}
result.push_back(0);
result.push_back(0);
return result;
}
};
int main()
{
//cout << "HELLO WORLD"<<endl;
Solution_2 s;
int a[3] = {3,2,4};
vector<int> nums;
vector<int> result;
for (int i=0;i < 3;i++)
{
nums.push_back(a[i]);
}
//vector<int>::iterator it = nums.begin();
//while (it<nums.end())
//{
// cout << *it << endl;
// it++;
//}
result = s.twoSum(nums, 6);
vector<int>::iterator its = result.begin();
while (its<result.end())
{
cout << *its <<" ";
its++;
}
system("pause");
return 0;
}