[LeetCode] Search a 2D Matrix II

240. Search a 2D Matrix II

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), j = matrix[0].size() - 1;
for(int i = 0; i < n and matrix[i][0] <= target; i++) {
while(matrix[i][j] > target) j--;
if(matrix[i][j] == target) return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/search-a-2d-matrix-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.