74. Search a 2D Matrix
by Botao Xiao
Question
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Thinking:
- Method1:从右上角开始遍历
- 如果temp大于target,左移。
- 如果temp小于target,下移。
- 如果等于,返回。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) return false;
int height = matrix.length;
int width = matrix[0].length;
int row = 0, col = width - 1;
while(row < height && col >= 0){
int temp = matrix[row][col];
if(temp == target) return true;
else if(temp < target)
row++;
else
col--;
}
return false;
}
}
二刷
这道题还是比较经典,二刷的完全可以记住一刷的结果。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int height = matrix.length, width = matrix[0].length;
int col = width - 1, row = 0;
while(row < height && col >= 0){
if(matrix[row][col] == target) return true;
else if(matrix[row][col] > target) col--;
else row++;
}
return false;
}
}
Subscribe via RSS