【LeetCode 001】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的元素,返回它们的下标值。
(输入保证有且仅有一个解,且同一个元素不能使用两次。)
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路:边读取边寻找。将数组的元素存进哈希数组中,每读入一个新元素x,在把x存进哈希数组的同时,在哈希数组中寻找是否有(target-x)存在,若存在则找到了解。由于本题需要返回原始数组中的下标值,所以用unordered_map<int,int>将数值按(值,原下标)来进行存储。

vector<int> twoSum(vector<int>& nums, int target) {
	unordered_map<int, int> hmap;
	for (int i = 0; i<nums.size(); i++) {
		auto p = hmap.find(target - nums[i]);
		if (p != hmap.end())
			return{ p->second,i };//用花括号可以直接返回vector
		hmap[nums[i]] = i;
	}
}

猜你喜欢

转载自blog.csdn.net/sinat_38972110/article/details/82923970