thewitchking

Untitled

Jul 17th, 2025
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4.  
  5. std::pair<int, int> twoSum(const std::vector<int>& nums, int target) {
  6.     std::unordered_map<int, int> seen; // key = number, value = index
  7.  
  8.     for (int i = 0; i < nums.size(); i++) {
  9.         int complement = target - nums[i];
  10.  
  11.         if (seen.find(complement) != seen.end()) {
  12.             return {seen[complement], i}; // return indices of the two numbers
  13.         }
  14.  
  15.         seen[nums[i]] = i;
  16.     }
  17.  
  18.     return {-1, -1}; // not found
  19. }
  20.  
  21. int main() {
  22.     std::vector<int> nums = {8, 3, 5, 7, 1};
  23.     int target = 10;
  24.  
  25.     std::pair<int, int> result = twoSum(nums, target);
  26.  
  27.     if (result.first != -1) {
  28.         std::cout << "Indices: " << result.first << ", " << result.second << "\n";
  29.         std::cout << "Numbers: " << nums[result.first] << " + " << nums[result.second] << " = " << target << "\n";
  30.     } else {
  31.         std::cout << "No pair found.\n";
  32.     }
  33.  
  34.     return 0;
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment