/**
* Start from the top-right corner, check
* if target > curr means we need to move to the next row b/c curr is the largest element in the row
* if target < curr means we need to move to the previous column b/c curr is the samllest element in the column
* each time we decrease the original problem by a row or column.
* Time O(m+n).
*/
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) return false;
// set curr as the top-right corner of the matrix
int row = 0;
int col = matrix[0].length-1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target) // move to the next row
row++;
else // move to the previous column
col--;
}
return false;
}
}
Leetcode 240. Search a 2D Matrix II
最新推荐文章于 2024-01-08 09:11:08 发布