Leetcode240. Search a 2D Matrix II
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
解法
从右上角开始找
如果当前数比目标元素大,当前列就不可能存在目标值,“指针”就向左移一格(纵坐标加1);
如果当前数比目标元素小,当前行就不可能存在目标值,“指针”就向下移一格(横坐标减 1)。
- 从右上角的元素开始找,如果这个元素比
target
大,则说明找更小的,往左走;如果这个元素比target
小,则说明应该找更大的,往下走。 - 如果某个时刻相等了,就说明找到了,如果一直走出矩阵边界了还没找到,则说明不存在。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length < 1 || matrix[0].length < 1){
return false;
}
int row = 0, col = matrix[0].length - 1;
//判断当前数组元素和target,如果当前大于target,往左走;小与target,往下走
while(row < matrix.length && col >= 0){
if(matrix[row][col] < target){
row++;
}else if(matrix[row][col] > target){
col--;
}else{
return true;
}
}
return false;
}
}