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

测试结果

相关推荐
什巳17 分钟前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
什巳3 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826523 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
巧克力男孩dd4 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒4 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵5 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒6 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术6 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo6 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花6 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活