编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
方法一:
思路
暴力循环 gogogo
- 循环每一行
- 循环每一行里面的每一个元素
- 找到了就
return true - 循环结束
return false
代码
var searchMatrix = function(matrix, target) {
for (let i = 0; i < matrix.length; i++) {
const list = matrix[i]
for (let j = 0; j < list.length; j++) {
const el = list[j]
if (el === target) return true
}
}
return false
};
// searchMatrix([[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], 5)
方法二:
思路
We start search the matrix from top right corner, initialize the current position to top right corner, if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too. We can rule out one row or one column each time, so the time complexity is O(m+n).
代码
var searchMatrix = function(matrix, target) {
// edgecase matric: null [] [[]]
if (!matrix || !matrix.length || !matrix[0].length) return false
let col = matrix[0].length - 1
let row = 0
while (col >= 0 && row < matrix.length) {
if (target === matrix[row][col]) return true
else if (target < matrix[row][col]) col--
else if (target > matrix[row][col]) row++
}
return false
};
解法引自 这里