我正在解决给Leetcode问题
我针对这个问题写了一段代码。该代码适用于给定的测试用例。但是当我尝试提交代码时,它给了我一个像这样的运行时错误
Line 1037: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/bits/stl_vector.h:1046:9
对于给定代码:
class Solution {
public:
int numberOfBeams(vector<string>& bank) {
int TotalBeam=0;
vector<int> occurOne;
for(int i=0;i<bank.size();i++)
{
int numOne=0;
for(int j=0;j<bank[i].length();j++)
{
if(bank[i][j]=='1')
numOne++;
}
if(numOne!=0)
occurOne.push_back(numOne);
}
for(int i=0;i<occurOne.size()-1;i++)
{
TotalBeam+=occurOne[i]*occurOne[i+1];
}
return TotalBeam;
}
};
我认为我的代码有问题。但是,尝试在我的本地 IDE 以及 programiz 在线 C++ 编译器以及 onlinegdb 编译器上运行代码,并且运行良好 因此我无法理解实际问题是什么?
只需添加一个条件 if (occurrOne.size() < 2){ return 0 }. Then the run time problem is solved.