【leetcode】力扣简单题两数之和

题目

思路

代码实现

cpp 复制代码
#include<iostream>
#include<unordered_map>

using namespace std;


class Solution
{
public:
	vector<int> TwoNumber(const vector<int>& nums, int target)
	{
		vector<int> number_vector;
		unordered_map<int, int> hash_table;
		for (int i = 0; i < nums.size() ; i++)
		{
			auto it = hash_table.find(target - nums[i]);
			if (it != hash_table.end())
			{
				number_vector.push_back(it->second);
				number_vector.push_back(i);
				return number_vector;
			}
			else
			{
				hash_table[nums[i]] = i;
			}
		}
	}
};

int main()
{
	Solution test;
	vector<int> number_vector = {2,6,11,12,7,8};
	vector<int> out = test.TwoNumber(number_vector, 9);
	for (auto var : out)
	{
		std::cout << "out:" << var << " " << std::endl;
	}
	return 0;
}

测试结果

相关推荐
浅念-20 小时前
递归解题指南:LeetCode经典题全解析
数据结构·算法·leetcode·职场和发展·排序算法·深度优先·递归
Kiling_070421 小时前
Java集合进阶:Set与Collections详解
算法·哈希算法
智者知已应修善业21 小时前
【51单片机89C51及74LS273、74LS244组成】2022-5-28
c++·经验分享·笔记·算法·51单片机
洛水水21 小时前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI1 天前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞1 天前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Dlrb12111 天前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora1 天前
Python 算法基础篇之集合
python·算法
平行侠1 天前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完1 天前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表