leetcode刷題

1.兩數之和

題目描述
給定一個整型數組,要求返回兩個數的下標,使得兩數之和等於給定的目標值,要求同一個下標不能使用兩次。
數據保證有且僅有一組解。

樣例
給定數組 nums = [2, 7, 11, 15],以及目標值 target = 9,

由於 nums[0] + nums[1] = 2 + 7 = 9,
所以 return [0, 1].

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<stack>
using namespace std;
class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int>res;
		map<int,int>mp;  //利用哈希表,減少時間複雜度
		for (int i = 0; i <nums.size(); i++)
		{
			int j = target - nums[i];
			//if (mp.find(j)!=mp.end())
			if (mp.count(j))
			{
				//auto m = mp.find(j);
				res = vector<int>({ mp[j],i });
			}
			mp[nums[i]] = i;
		}
		return res;
	}
};
int main()
{
	vector<int>a;
	//a.push_back(1);
	//a.push_back(3);
	//a.push_back(5);
	//a.push_back(7);
	a = vector<int>({1,3,5,7});
	Solution b;
	vector<int>c;
	c=b.twoSum(a,10);
	for (int j = 0; j < c.size(); j++)
		cout << c[j]<<' ';
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章