【问题标题】:C++: Every time, the function is returning empty vector. Why?C++:每次,函数都返回空向量。为什么?
【发布时间】:2020-07-26 22:21:39
【问题描述】:

我一直在尝试解决这个问题:

给定一个整数数组,返回两个数字的索引 它们加起来就是一个特定的目标。

您可以假设每个输入都有完全一个解决方案, 并且您不能两次使用相同的元素。

示例:

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

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

我一直在尝试使用map 解决这个问题,我尝试的解决方案如下:

#include <iostream>
#include <map>
#include <vector>

using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    std::map<int, int> indices;

    for (int i = 0; i < nums.size(); ++i) {
        auto it = indices.find(target - nums[i]);

        if (it != indices.end())
            return {it->first, i};

        indices[i] = nums[i];
    }
    return {};
}

int main() {
    std::vector<int> nums = {2, 7, 11, 15};
    int target = 9;

    std::vector<int> ans = twoSum(nums, target);

    for(const auto &elem : ans) {
        std::cout << elem << " ";
    }
    std::cout << "\n";

    return 0;
}

为了避免两个 for 循环,我试图找到 target - num2,因为 num1 + num2 = target。

所以,逻辑是

  • 从输入向量nums创建地图
  • 使用map.find(target - num[i])
  • 返回指向target-nums[i]的迭代器的第一个值,即映射中value = target-nums[i]的keyi

因此,对于上面的代码,函数应该返回{0, 1}

但是,每次我都会得到一个空向量。谁能告诉我是我的逻辑错误还是我错误地操纵了地图或矢量?

【问题讨论】:

  • 您是否尝试过在调试器中单步执行您的程序?或者添加更多 cout 语句来显示运行时的值是什么?如果您想编写任何重要的程序,这是您需要学习的基本故障排除过程。如果您可以确定一条特定的线路没有按照您的意愿执行,并且您不明白为什么,那么可以在这里询问。
  • 当您执行indices.find(target - nums[i]) 时,您假设键是数字,值是索引。但是当您执行indices[i] = nums[i] 时,您会假设相反。弄清楚你想走哪条路,并保持一致。
  • 哦,是的,你是绝对正确的@Igor Tandetnik。太感谢了。我想我必须更好地理解map.find()
  • @Paul Sanders,但是如何使用set 保存/获取两个索引?

标签: c++ algorithm dictionary data-structures stl


【解决方案1】:

您非常接近解决问题,但您的代码有一个小而关键的问题。

您将元素添加到地图中为 (key=index, value=number)

indices[i] = nums[i];

...本质上,您只是以不同的格式重新创建了数组,所以如果您考虑一下,对于每个inums[i] == indices[i]。这种方法确实无法进一步解决您的问题。

相反,您应该尝试映射 (key=number, value=index)

indices[nums[i]] = i;

这样,当您在地图上搜索以前遇到的号码时,您已经是

auto it = indices.find(target - nums[i]);

...您最终会搜索数字本身而不是索引!

请注意,您还需要更改返回以使用 index 而不是 value,因为您的地图格式现在不同了

auto it = indices.find(target - nums[i]);
if (it != indices.end())
    return {it->second, i};

【讨论】:

    【解决方案2】:

    尝试做:indices[num[i]] = 1

    您正在使用索引作为地图的键,但您确实应该使用值。

    【讨论】:

    • 你是说indices[num[i]] = i 吗?
    【解决方案3】:

    根本不要使用地图。

    std::vector<int> twoSum(const std::vector<int> & nums, int target) {
        for (int it1 = nums.begin(); it1 != nums.end(); ++it1) {
            auto it2 = std::find(std::next(it1), nums.end(), target - *it1);
    
            if (it2 != nums.end())
                return {std::distance(nums.begin(), it1), std::distance(nums.begin(), it2)};
        }
    
        // You can assume this is never reached, throwing is noisier than returning empty
        throw std::runtime_error("invalid arguments to twoSum");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-16
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      相关资源
      最近更新 更多