Please click here to debug the problem
#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> numMap;
int n = nums.size();
// Build the hash table
for (int i = 0; i < n; i++) {
numMap[nums[i]] = i;
}
// Find the complement
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (numMap.count(complement) && numMap[complement] != i) {
//if (numMap.find(complement) != numMap.end() && numMap[complement] != i) {
return {i, numMap[complement]};
}
}
return {}; // No solution found
}
};
int main()
{
Solution sol;
vector<int> nums = {2,7,11,15};
vector<int> result = sol.twoSum(nums, 9);
cout << "{2, 7, 11, 15} - ";
for (auto i : result) {
cout << i << " ";
}
cout << endl;
nums = {3, 2, 4};
result = sol.twoSum(nums, 6);
cout << "{3, 2, 4} - ";
for (auto i : result) {
cout << i << " ";
}
return 0;
}
Input
nums =
[3,2,4]
target =
6
Output
[1,2]
Expected
[1,2]
[1,2]
Comments
Post a Comment