【C++练习】两数之和

题目:两数之和

描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

要求

编写一个函数 twoSum,该函数接收一个整数向量 nums 和一个整数 target,返回一个包含两个整数的向量,表示在 nums 中和为目标值 target 的两个数的索引。

源代码:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    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 {};
}

int main() {
    // 测试用例 1
    vector<int> nums1 = { 2, 7, 11, 15 };
    int target1 = 9;
    vector<int> result1 = twoSum(nums1, target1);
    cout << "测试用例 1 输出: [";
    for (int index : result1) {
        cout << index << " ";
    }
    cout << "]" << endl;

    // 测试用例 2
    vector<int> nums2 = { 3, 2, 4 };
    int target2 = 6;
    vector<int> result2 = twoSum(nums2, target2);
    cout << "测试用例 2 输出: [";
    for (int index : result2) {
        cout << index << " ";
    }
    cout << "]" << endl;

    // 测试用例 3
    vector<int> nums3 = { 3, 3 };
    int target3 = 6;
    vector<int> result3 = twoSum(nums3, target3);
    cout << "测试用例 3 输出: [";
    for (int index : result3) {
        cout << index << " ";
    }
    cout << "]" << endl;

    return 0;
}

运行截图:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值