TwoSum c++ Map 已AC

本文介绍了一种使用unordered_map数据结构解决数组中两数之和等于特定目标值的问题,通过映射元素位置,提高了查找效率,避免了传统双层循环的低效方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:
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 

解题思路:

刚看到这道题目时,很快用两个for语句解了出来,但AC不通过。报告runtime error,是的,它花了O(n*n);

我又尝试调用sort函数,先把数组排序,排完序后使用二分法,还是报告runtime error,二分法代码如下:



struct Node
{
	int num,pos;
};

bool cmp(Node a,Node b)
{
	return a.num < b.num;
}
class Solution1
{
public:
	vector<int> twoSum(vector<int> &numbers, int target) 
	{
		vector<int> result;
		vector<Node>array;
		int i,j,k,index1,index2;
		k = sizeof(numbers)/sizeof(numbers[0]);
		for(i = 0; i < k; i++)
		{
			Node temp;
			temp.num = numbers[i];
			temp.pos = i + 1;
			array.push_back(temp);
		}
		sort(array.begin(),array.end(),cmp);
		for(int i = 0, j = array.size() -1; i != j;)
		{
			int sum = array[i].num + array[j].num;
			if(sum == target)
			{
				index1 = array[i].pos;
				index2 = array[j].pos;
				result.push_back(index1);
				result.push_back(index2);
				break;
			}
			else if(sum < target)
			{
				++i;
			}
			else
				--j;
				
		}
	    return result;
	}
};


==============================================================

只能搜别人的方法了== 好吧,大家都直接调用Map,果然AC地过去,可是我根本不认识Map!简洁地不敢相信==都怪书读的太少==

class Solution
{
public:
	vector<int> twoSum(vector<int> &numbers, int target) 
	{
		vector<int> result;
		unordered_map<int,int> num_to_pos;
		for(int i = 0; i < numbers.size(); ++i)
		{
			int temp = target - numbers[i];
			if(num_to_pos.find(temp) != num_to_pos.end())
			{
				result.push_back(num_to_pos[temp]);
				result.push_back(i + 1);
				return result;
			}
			else
			{
				num_to_pos[numbers[i]] = i + 1;
			}
		}
	   return result;
	}
};

那么什么是unordered_map呢?

C++ Primer里是这么写的:

这是新标准定义的四个无序关联容器之一。这些容器不是使用比较运算符来组织元素,而是使用一个哈希函数和关键字类型的==运算符。在关键字类型的元素没有明显的顺序关系的情况下,无序容器是非常有用的。

无序容器提供了与有序容器相同的操作(find,insert,erase等)。

map和set举例

#include<iostream>
#include<map>
#include<vector>
#include<string>
#include<set>
using namespace std;

void map_test()
{
	map<string,size_t> word_count;
	string word;
	while(cin >> word)
	{
		++word_count[word];
	}
	for(const auto &w :word_count)
	{
		cout<<w.first <<"  occurs  "<<w.second
			<<((w.second > 1) ?"times":"time")<<endl;
	}
}

void set_test()
{
	map<string,size_t>word_count;
	set<string> exclude;// = {"the","but","and","or","a","an","The","But","And","Or","A","An"};
	exclude.insert("the");
	exclude.insert("The");

	string word;
	while(cin>>word)
	{
		if(exclude.find(word) == exclude.end()) //只统计不在exclude中的单词
		{
			++word_count[word];
		}
	}
	for(const auto &w :word_count)
	{
		cout<<w.first <<"  occurs  "<<w.second
			<<((w.second > 1) ?"times":"time")<<endl;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值