【问题标题】:Why am i getting runtime error in leetcode? [closed]为什么我在 leetcode 中出现运行时错误? [关闭]
【发布时间】:2022-01-23 05:33:47
【问题描述】:

我在解决 leetcode 上的问题(217.Contains Duplicate)时遇到此错误

AddressSanitizer:DEADLYSIGNAL
=================================================================
==33==ERROR: AddressSanitizer: stack-overflow on address 0x7ffed3a8f0d8 (pc 0x0000003454ba bp 0x7fff8d5591f0 sp 0x7ffed3a8f0e0 T0)
    #2 0x7f8de24cc0b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
==33==ABORTING

这是我的代码:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        long long int n=2*1e9+10;
        long long int hsh[n];
        for (int i=0;i<sizeof(nums);++i){
            hsh[nums[i]+n]++;
        }
        int ok=0;
        for(int i=0;i<n;++i){
            if(hsh[i]>1){
                ok=1;
                break;
            }
        }
        if(ok==1){return true;}
        else{return false;}
    }
};

【问题讨论】:

  • sizeof(nums) 绝对错误,应该改为nums.size()
  • 看起来你正在以另一种语言的背景进入 C++。您不必完全使用 Yoda 并忘记所学的内容,但您必须花一些时间来学习如何以 C++ 的方式做事。你不会从比赛现场的裁判程序中得到这些。我强烈推荐few good books
  • 旁注:如果n 是编译时已知的常量,long long int hsh[n]; 在标准 C++ 中才合法。 long long int n=2*1e9+10; 在技术上不是,所以除非你把它改成类似constexpr long long int n=2*1e9+10; 的东西,否则在使用不支持Variable Length Arrays 的工具构建时会出现编译器错误。请注意,将n 设为常量并不能解决它太大的问题。

标签: c++ hash runtime-error c++14


【解决方案1】:

hsh 对于堆栈来说太大了。使用std::vector

这也是错误的:sizeof(nums)。你想要nums.size()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多