/*
* @lc app=leetcode id=240 lang=javascript
*
* [240] Search a 2D Matrix II
*
* https://leetcode.com/problems/search-a-2d-matrix-ii/description/
*
*
*/
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
if (!matrix || matrix.length === 0) return false;
let colIndex = 0;
let rowIndex = matrix.length - 1;
while (rowIndex > 0 && target < matrix[rowIndex][colIndex]) {
rowIndex--;
}
while (colIndex < matrix[0].length) {
if (target === matrix[rowIndex][colIndex]) return true;
if (target > matrix[rowIndex][colIndex]) {
colIndex++;
} else if (rowIndex > 0) {
rowIndex--;
} else {
return false;
}
}
return false;
};
Python Code:
class Solution:
def searchMatrix(self, matrix, target):
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
i = m - 1
j = 0
while i >= 0 and j < n:
if matrix[i][j] == target:
return True
if matrix[i][j] > target:
i -= 1
else:
j += 1
return False