【问题标题】:Runtime error: reference binding to null pointer of type 'int' [closed]运行时错误:引用绑定到“int”类型的空指针 [关闭]
【发布时间】:2020-06-27 15:02:09
【问题描述】:

我正在解决 Leetcode 上的 House Robber 问题,我收到“运行时错误:引用绑定到类型为‘int’的空指针”。为什么会出现这个错误?

我的代码:

  class Solution {
  public:
    int rob(vector<int>& a) {
        int n=a.size();
        vector<int> dp(n);
        for(int i=0;i<n;i++)
            dp.push_back(0);
        dp[0]=a[0]; dp[1]=a[1];
        int ans=0;
        for(int i=2;i<n;i++)
        {
            dp[i]+=dp[i-2]+a[i];
            ans=max(ans,dp[i]);
        }
            
        return ans;
    }
};

【问题讨论】:

    标签: c++ algorithm rte


    【解决方案1】:

    您需要注意输入大小。对于dp[0]=a[0]; dp[1]=a[1];,您假设输入的大小至少为 2。

    是这样吗?那就没事了,不然程序会像你描述的那样崩溃。

    通常这些Leetcode 问题是您需要处理所有 极端情况。也许您的解决方案适用于一般情况,但您还应该考虑烦人的输入(空列表、具有一个元素的列表等...)

    【讨论】:

    • 但是 codeforces 或其他平台不这样做对吗?这是 leetcode 独有的东西吗?
    • @AdityaKarad,我不知道其他平台。 Leetcode 做到了(根据经验)。但他们这样做是有道理的 - 您的解决方案应该对所有输入都具有鲁棒性。
    • 问题中的约束是0 &lt;= nums.length &lt;= 100,所以你肯定可以得到零元素的输入列表。那你就有问题了。
    • @AdityaKarad 但 codeforces 或其他平台做不到这一点 -- 它与其他平台无关。在 C++ 中越界访问元素会导致未定义的行为
    【解决方案2】:

    空指针放在一边,你可以用更高效的算法解决这个问题,而不需要使用dp数组(在常量内存中):

    class Solution {
    public: 
        int rob(const std::vector<int>& nums) {
            int length = nums.size();
            if (length == 0) {
                return 0;
            }
    
            int prev = 0;
            int curr = 0;
            int temp;
            for (int index = 0; index < length; index++) {
                temp = std::max(curr, prev + nums[index]);
                prev = curr;
                curr = temp;
            }
    
            return curr;
        }
    };
    

    参考文献

    • 有关其他详细信息,您可以查看Discussion Board。里面有大量公认的解决方案、解释、提示、多种语言的高效算法,以及时间/空间复杂度分析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-03
      • 2019-11-17
      • 1970-01-01
      • 2020-01-03
      相关资源
      最近更新 更多