unordered_map 是關聯容器,含有帶唯一鍵的鍵-值 pair 。搜索、插入和元素移除擁有平均常數時間複雜度。
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].
代码:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <iterator>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
int n = (int)nums.size();
/* 这个不能跳过当前, 会造成,例如target 6, map中含3,会finf 6-3=3
两个3其实是一个3
for (int i = 0; i < n; i++) {
map[nums[i]] = i;
}
*/
for (int i = 0; i < n; i++) {
auto p = map.find(target - nums[i]);
if (p != map.end()) {
return { p->second + 1, i + 1 };
}
// map[nums[i]] = i;
}
return {};
}
};
int main()
{
//int arr[100] = {0};
//cout << arr[0] << " " << arr[1]<<" "<<arr[100];
Solution m_sol;
vector<int> nums = {3, 2, 4}; //{2, 6, 11, 15, 12, 7};
vector<int> m_return;
m_return = m_sol.twoSum(nums, 6);
if (m_return.size() == 0) {
cout << "failed" << endl;
}
for (int a: m_return) {
cout << a << endl;
}
return 0;
}