DEV Community

海前 王
海前 王

Posted on

letcode 1

#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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)