#include <iostream>
#include <vector>
#include <unordered_map>
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> numToIndex;
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (numToIndex.find(complement) != numToIndex.end()) {
return { numToIndex[complement], i };
}
numToIndex[nums[i]] = i;
}
return {}; // No solution found
}
};
int main() {
std::vector<int> nums = { 3, 7, 11, 15 };
int target = 9;
Solution solution;
std::vector<int> result = solution.twoSum(nums, target);
if (!result.empty()) {
std::cout << "Indices: " << result[0] << ", " << result[1] << std::endl;
std::cout << "Numbers: " << nums[result[0]] << ", " << nums[result[1]] << std::endl;
}
else {
std::cout << "No solution found." << std::endl;
}
return 0;
}
This site is built on Heroku
Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)