This content originally appeared on DEV Community and was authored by 海前 王
#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 content originally appeared on DEV Community and was authored by 海前 王
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.

APA
MLA
海前 王 | Sciencx (2024-08-27T01:45:22+00:00) letcode 1. Retrieved from https://www.scien.cx/2024/08/27/letcode-1/
" » letcode 1." 海前 王 | Sciencx - Tuesday August 27, 2024, https://www.scien.cx/2024/08/27/letcode-1/
HARVARD海前 王 | Sciencx Tuesday August 27, 2024 » letcode 1., viewed ,<https://www.scien.cx/2024/08/27/letcode-1/>
VANCOUVER海前 王 | Sciencx - » letcode 1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/27/letcode-1/
CHICAGO" » letcode 1." 海前 王 | Sciencx - Accessed . https://www.scien.cx/2024/08/27/letcode-1/
IEEE" » letcode 1." 海前 王 | Sciencx [Online]. Available: https://www.scien.cx/2024/08/27/letcode-1/. [Accessed: ]
rf:citation » letcode 1 | 海前 王 | Sciencx | https://www.scien.cx/2024/08/27/letcode-1/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.