LeetCode算法c++刷题-twoSum

今日刷题

在数组找到2个数之和等于给定值的数字,结果返回2个数字在数组中的下标。

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

解题思路:

顺序扫描数组,对每⼀个元素,在 map 中找能组合给定值的另⼀半数字,如果找到了,直接返回 2 个
数字的下标即可。如果找不到,就把这个数字存⼊ map 中,等待扫到“另⼀半”数字的时候,再取出来返
回结果。

示例代码:

class twoSum 
{
    
    
public:
	vector<int> twoSum(vector<int>& nums, int target) 
	{
    
    
		unordered_map<int, int> hamap;
		int x = -1;
		for(int i = 0; i < nums.size(); i++)
		{
    
    
			x = target - nums[i];
			if(hamap.find(x) != hamap.end())
			{
    
    
				return {
    
    hamap.find(x)->second, i};
			}
			hamap[num[i]] = i;
		}
		return {
    
    };
	}
}

注意:

map中存入的nums为key,nums下标为值
eg:
hamap = { {2,0},{7,1},{11,2},{15,3}}

猜你喜欢

转载自blog.csdn.net/u010196944/article/details/127567321