LeetCode#1. 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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

问题大意:给定一个整形数组和目标和target,返回数组中,两个数的和等于目标和target的下标。(输入保证只有一个合法的解)

解题思路:直接hash, 把每个数作为key,下标作为值,放入hash表,然后遍历的时候找target – x。

#include<vector>
#include<iostream>
#include<map>
#include<iterator>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
	map<int, int> vis;
	for (int i = 0; i < nums.size(); i++) {
		if (vis.find(target - nums[i]) != vis.end())
			return vector<int>{vis[target - nums[i]], i};
		vis[nums[i]] = i;
	}
	return vector<int>{-1, -1};
}

void test_twoSum(){
	vector<int> v1,v2;
	v1.push_back(2);
	v1.push_back(7);
	v1.push_back(11);
	v1.push_back(3);
	v1.push_back(32);

	int target = 9;
	v2 = twoSum(v1, target);
	for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++){
		cout << *it << endl;
	}
}

int main(){
	test_twoSum();
	getchar();
}

猜你喜欢

转载自blog.csdn.net/akenseren/article/details/80489571
今日推荐