搜索二維矩陣,針對一個從左到右拄氯,從上到下遞增的二維矩陣灭返,在元素中查找指定值的元素。
初始化一個指向指針左下角的指針坤邪,當(dāng)前的值大于目標(biāo)值熙含,向上移動一行,當(dāng)前的值大于目標(biāo)值艇纺,向右移動一列怎静。這種方式將最終找到可搜索的值。選左上角黔衡,像右增大蚓聘,向上減小,選右下角盟劫,向下增大夜牡,向左減小。
時間復(fù)雜度:O(m + n)
空間復(fù)雜度:O(1)
- Runtime: 740 ms, faster than 45.67%
- Memory Usage: 42 MB, less than 49.53%
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
let m = matrix.length
let n = matrix[0].length
let row = m - 1
let col = 0
while(row >= 0 && col < n) {
const cur = matrix[row][col]
if(cur < target) {
col++
} else if(cur > target) {
row--
} else {
return true
}
}
return false
};