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].


思路:

找到 a,找到 b,讓 a + b = target。那麼肯定得遍歷,遍歷的過程中,記錄什麼,成了思考的關鍵。

既然是配對,那麼 kv 結構是非常合適的,於是上了 Hash 表。讓 key 就是要找的 b,讓 value 記錄 a 的 index,也就是結果需要的索引。


代碼:


#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

/*
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].
*/




class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		unordered_map<int, int> record;
		for (int i = 0; i != nums.size(); i++)
		{
			auto find = record.find(nums[i]);
			if (find != record.end())
				return{ find->second, i };
			else
				record.emplace(target - nums[i], i);
		}

		return{ -1, -1 };
	}
};

發佈了33 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章