The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target =3
, Returntrue
.
This is an young matrix, that is, each row is incremental, and each column is incremental. Based on the incremental nature, we only search for the last number for each row. If it is smaller than target, we will go to the next row. If it is greater than target, it will be in this row, so we will go to the previous column, until this number is found.
class Solution {public: bool searchMatrix(vector
> &matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); for(int row = 0, col = n-1; row < m && col >= 0;) { if(matrix[row][col] < target) { row++; } else if(matrix[row][col] > target) { col--; } else return true; } return false; }};
The difficulty of this question is medium. Originally, I planned to finish the easy difficulty first, considering the moderate difficulty. I accidentally watched the video of the July algorithm (sorting and searching practices) and benefited a lot. I decided to consolidate and digest the examples I had talked about. So I did this question first, and the idea of the algorithm came from Cao Bo, learning!