leetcode-two sum

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;
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值