# 一、解题思路

#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int i = matrix.size() - 1, j = 0;
while (i >= 0 && j < matrix[0].size())
{
if (matrix[i][j] > target)
i--;
else if (matrix[i][j] < target)
j++;
else return true;
}
return false;
}
};

int main() {

Solution s;
vector<vector<int>> matrix{  };
int target = 5;
bool ans = s.findNumberIn2DArray(matrix, target);
cout << boolalpha << ans << endl;
system("pause");
}



# 二、错误

## 1.错误示范

class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {

int r = 0;
int c = matrix[0].size() - 1 ;

while(r < matrix.size() && c >= 0){
if(matrix[r][c] > target)
c--;
else if(matrix[r][c] < target)
r++;
else
return true;
}
return false;
}
};


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

## 2.错误分析

LeetCode的测试中还包括二维数组为空[ ] ，在此时matrix.size()会显示为0，而matrix[0].size()就会报错！！！

#include<iostream>
#include<vector>
using namespace std;

int main() {
vector<vector<int>>arr{};
int a = arr.size();//注意
cout << a << endl;
system("pause");
}


#include<iostream>
#include<vector>
using namespace std;

int main() {
vector<vector<int>>arr{};
int a = arr[0].size(); //注意
cout << a << endl;
system("pause");
}



int main() {
vector<vector<int>>arr{ { } };// ！！！
int a = arr[0].size();
cout << a << endl;
system("pause");
}


class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int i = matrix.size() - 1, j = 0;
while (i >= 0 && j < matrix[0].size())
{
if (matrix[i][j] > target)
i--;
else if (matrix[i][j] < target)
j++;
else return true;
}
return false;
}
};


## 3.错误改正

class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {

if(matrix.size() < 1 || matrix[0].size() < 1 )
return false;

int r = 0;
int c = matrix[0].size() - 1 ;

while(r < matrix.size() && c >= 0){
if(matrix[r][c] > target)
c--;
else if(matrix[r][c] < target)
r++;
else
return true;
}
return false;
}
};



# 总结

1.注意二维数组中vector为{ }以及{ { } }的情况。其中

• vector为{ }，matrix[0].size()报错。
• vector为{ { } }，matrix[0].size()为0。

2.即使vector为{ }，但是matrix[0].size()用在if( )条件判断中还是可以用的。

• 0
点赞
• 0
评论
• 1
收藏
• 一键三连
• 扫一扫，分享海报

08-02 2万+

10-13 3520
07-29 223
09-05 4612
11-11 175
01-27 32
04-29 40
01-27 453
09-19 212
06-04 62
05-30 637
12-23 513

D逆光

¥2 ¥4 ¥6 ¥10 ¥20