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

测试结果

相关推荐
IronMurphy4 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬4 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership5 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826525 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
山甫aa5 小时前
差分数组 ----- 从零开始的数据结构
数据结构
早日退休!!!5 小时前
《数据结构选型指南》笔记
数据结构·数据库·oracle
Beginner x_u5 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
丑八怪大丑6 小时前
Java数据结构与集合源码
数据结构
_深海凉_8 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录9 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode