LeetCode-2.Add_Two_Numbers_.../main.cpp
2025-03-28 20:10:42 +00:00

17 lines
564 B
C++

#include <vector>
#include <unordered_map>
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> num_map; // Stores number and its index
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (num_map.find(complement) != num_map.end()) {
return {num_map[complement], i}; // Found the two indices
}
num_map[nums[i]] = i; // Store index of the current number
}
return {};
}
};