編寫(xiě)一個(gè)高效的算法來(lái)搜索 m x n 矩陣 matrix 中的一個(gè)目標(biāo)值 target。該矩陣具有以下特性:
每行的元素從左到右升序排列。
每列的元素從上到下升序排列。
示例:
現(xiàn)有矩陣 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。
思路:以左下角的數(shù)為基準(zhǔn),小于目標(biāo)值,則向右移動(dòng),大于目標(biāo)值,則向上移動(dòng)
代碼:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length-1;
int col = 0;
while (row>=0 && col<=matrix[0].length-1){
if (matrix[row][col] == target){
return true;
}else if (matrix[row][col] > target){
row--;
}else{
col++;
}
}
return false;
}
}