Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> heap;
for(int i= 0; i < nums.size(); i++){
int r = target - nums[i];
if(heap.count(r)){
return {heap[r], i};
} else {
heap[nums[i]] = i;
}
}
return {};
}
};
int main() {
vector<int> nums = {11,2,7,15};
int target = 9;
Solution solution; // = *new Solution;
vector<int> result = solution.twoSum(nums, 9);
if(result.size() == 2){
std::cout << "result = " << result[0] << ", " << result[1] << std::endl;
} else {
std::cout << "not found" << std::endl;
}
return 0;
}