leetcode_1题——Two Sum(哈希表hashtable,map)

Two Sum

  Total Accepted: 81397 Total Submissions: 459615My Submissions

 

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

Hide Tags
  Array Hash Table
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

开始想直接按正常的最简单方法两个循环来做,结果发现提交时,超出了内存,显然这道题不能这样做

接下来,又想是不是顺序的,就把后面的数给砍掉,结果发现是无需的数列

在接下来,又想把比目标数字大的全部砍掉,结果发现有负数,这种方法也不行。

lass Solution {

public:

    vector<int> twoSum(vector<int> &numbers, int target) {

        	vector<int> last_result;

	vector<int> temp;

	int len=numbers.size();

	int realy_size;

	for(int i=0;i!=len;i++)

	{

		if(numbers[i]<target)

		{

			realy_size=i;

			temp.push_back(numbers[i]);

		}

	}

	realy_size=temp.size();

	for(int i=0;i!=realy_size-1;++i)

	{

		for(int j=i+1;j!=realy_size;++j)

		{

			if(numbers[i]+numbers[j]==target)

			{

				last_result.push_back(i+1);

				last_result.push_back(j+1);

				return last_result;

			}

		}

	}

	return last_result;

    }

};

  看来非得需要用hash表来做

#include<iostream>

#include<vector>

#include<map>

#include<utility>

using namespace std;



/*

由于哈希表中的查找的时间复杂度为O(1),所以讲numbers[i]作为键值,将i作为value值

在一次循环过程中,查找前面是否有重复的键值,以及看是否有target-numbers[i]相等的值,若有

这说明已经找到了

*/

vector<int> twoSum(vector<int> &numbers, int target) {

	vector<int> last_result;

	map<int,int> hash_table;

	hash_table.insert(pair<int,int>(numbers[0],0));



	for(int i=1;i!=numbers.size();++i)

	{

		if(hash_table.count(target-numbers[i])==1)//看是否有target-numbers[i]相等的值

		{

			int n=hash_table[target-numbers[i]];

			last_result.push_back(n+1);

			last_result.push_back(i+1);

			break;

		}

		if(hash_table.count(numbers[i])==0)//找前面是否有重复的键值

			hash_table.insert(pair<int,int>(numbers[i],i));

	}

	return last_result;

}



int main()

{

	vector<int> numbers;

	numbers.push_back(3);numbers.push_back(2);numbers.push_back(4);

	int target;

	target=6;

	vector<int> last_reault;

	last_reault=twoSum(numbers,target);

	cout<<last_reault[0]<<' '<<last_reault[1]<<endl;



	system("pause");

	return 1;



}

  

你可能感兴趣的:(Hashtable)