1.TwoSum

本文介绍了一种经典的算法问题——寻找数组中两个数相加等于特定目标值的方法。提供了两种解决方案,一种是通过双重循环查找,时间复杂度为O(n^2),另一种是利用哈希表提高效率至O(n)。并附上了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return[0, 1].

(给定一个整型数组,返回其中和为指定数值的两个数的下标。
假定输入数组有唯一解,且不能使用同一个数两次。)

找到一个数组中和为指定数值的两个数并不难,遍历数组中的元素即可,实现起来并不难。

解法一:

vector<int> TwoSum::TwoSum1(vector<int>& nums, int target)
{
    vector<int> result;
    for (int i = 0; i < nums.size(); i++)
    {
        for (int j = i + 1; j < nums.size(); j++)
        {
            if (nums[i] + nums[j] == target)
            {
                result.push_back(i);
                result.push_back(j);
                return result;
            }
            else if (nums[i] + nums[j] > target)
            {
                break;
            }
        }
    }
    return result;
}

上述解法的时间复杂度为O(n^2)。
OJ是不会让它过的。

解法二:

#include <unordered_map>

vector<int> TwoSum::TwoSum2(vector<int>& nums, int target)
{
    vector<int> result;
    // 创建一个哈希表
    unordered_map<int, int> hash;
    for (int i = 0; i < nums.size(); i++)
    {
        // 遍历时直接查找对应值是否存在哈希表中
        int targetNum = target - nums[i];
        if (hash.find(targetNum) != hash.end())
        {
            result.push_back(hash[targetNum]);
            result.push_back(i);
            return result;
        }
        // 哈希表的键值对为:数组中元素的值,该元素的下标值
        // 这样在查找到两个数的时候便于返回下标
        hash[nums[i]] = i;
    }

    return result;
}

上述代码即可Accept。

测试代码:

    TwoSum twoSum;
    vector<int> input{ 2, 7, 11, 15 };
    vector<int> result = twoSum.TwoSum1(input, 9);
    //vector<int> result = twoSum.TwoSum2(input, 9);
    for (vector<int>::iterator it = result.begin(); it != result.end(); ++it)
    {
        cout << *it << "\n";
    }
    cout << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值