Leetcode剑指Offer04:二维数组中的查找(以右上角作为起点)
问题描述:
在刷leetcode时遇到二维数组中的查找这个题目,当使用右上角作为起点实现查找时执行结果都是正确的但是提交时显示编译错误,出现空指针操作。但以左下角作为起点时可以顺利通过
当以右上角作为起点时提交时报错内容为:Line 1033: Char 9: runtime error: reference binding to null pointer of type ‘std::vector<int, std::allocator>’ (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/…/lib/gcc/x86_64-linux-gnu/9/…/…/…/…/include/c++/9/bits/stl_vector.h:1043:9
原始提交代码为:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
//设置查找右上角为查找起点
int rowIndex = 0;
int colIndex = matrix[0].size()-1;
while(rowIndex<matrix.size()&&colIndex>=0)//设置查找终点为左下角
{
if(matrix[rowIndex][colIndex]==target)
{
return true;
}
else if(matrix[rowIndex][colIndex]>target)
colIndex--;
else
rowIndex++;
}
return false;
}
};
原因分析:
当matrix[0].size()=0时,colIndex的初始值为-1,会导致后续matrix[rowIndex][colIndex]越界。
解决方案:
加入if语句进行判断:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
//设置查找右上角为查找起点
if(matrix.size()==0||matrix[0].size()==0)
return false;
int rowIndex = 0;
int colIndex = matrix[0].size()-1;
while(rowIndex<matrix.size()&&colIndex>=0)//设置查找终点为左下角
{
if(matrix[rowIndex][colIndex]==target)
{
return true;
}
else if(matrix[rowIndex][colIndex]>target)
colIndex--;
else
rowIndex++;
}
return false;
}
};