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

测试结果

相关推荐
phltxy9 小时前
C语言操作符详解
java·c语言·算法
aqiu11111110 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye10 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考11 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾11 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研12 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a1879272183113 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_9622974814 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye14 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展