LeetCode的TWO-SUM(一)

/*Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
描述:给定一个整数数组和一个值target,求两个下标i、j,使得a[i] + a[j] = target,返回下标。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return[0, 1].
*/
/*
小知识点:
vector算一个动态数组,属于类模板;
无序映射是关联容器,用于存储由键值和映射值组合而成的元素,并允许基于键快速检索各个元素。
在unordered_map中,键值通常用于唯一标识元素,而映射值是与该键关联的内容的对象。键和映射值的类型可能不同。
在内部,unordered_map中的元素没有按照它们的键值或映射值的任何顺序排序,而是根据它们的散列值组织成桶以允许通过它们的键值直接快速访问单个元素(具有常数平均时间复杂度)。
*/
#include <iostream>
#include <unordered_map>
using namespace std;
using std::unordered_map;
using std::vector;
class Solution
{
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		unordered_map<int, int> hash;
		vector<int> result;
		for (int i = 0; i<nums.size(); i++)
		{
			int numToFind = target - nums[i];
			/*
			用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,
			它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭
			代器等于end函数返回的迭代器,
			若有unordered_map <int, int> mp;查找x是否在map中
			方法1:  若存在  mp.find(x)!=mp.end()
			方法2:  若存在  mp.count(x)!=0
			*/
			//if发现map中的数字,返回它们
			if (hash.find(numToFind) != hash.end()) {
				result.push_back(hash[numToFind]);
				result.push_back(i);
				return result;
			}
			//如果没有发现数字,把它放在map中
			hash[nums[i]] = i;
		}
		return result;
	}
};

int main() {
	Solution s;
	vector < int > vi = { 2,7,11,15};
	int target = 9;
	vector<int> t=s.twoSum(vi, target);
	for (vector<int>::iterator it = t.begin(); it != t.end(); it++)
	{
		std::cout << *it<<" ";
	}
}

运行时间:4ms

时间空间复杂度都是O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值