剑指 Offer 04. 二维数组中的查找
在一个 n * m
的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 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
。
限制:
0 < = n < = 1000 0 <= n <= 1000 0<=n<=1000
0 < = m < = 1000 0 <= m <= 1000 0<=m<=1000
注意
:本题与主站 240 题相同:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
解题思路
因为右上角的数字,是当前列的最小值,当前行的最大值,所以可以用变相的二分思想
。
- 从右上角开始,首先选中右上角的数字,如果该数字等于要查找的数字,则查找过程结束。
- 如果该数字大于
target
,则剔除该数字所在的列,因为这一列中的数字都会大于target
。 - 如果该数字小于
target
则剔除该数字所在的行,因为这一行中的数字都会小于target
。
Java代码
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int rows = matrix.length;
int cols = matrix[0].length;
//左上角起始坐标
int row = 0;
int col = cols -1;
while(row < rows && col >= 0){//保证不越界
if(matrix[row][col] == target){
return true;
}else if(matrix[row][col] > target){
col--;//把查找范围剔除该列
}else{
row++;//把查找范围剔除该行
}
}
return false;//矩阵遍历结束都没有找到,返回false
}
}
go代码
func findNumberIn2DArray(matrix [][]int, target int) bool {
if matrix == nil || len(matrix) == 0 {return false}
row,col := len(matrix),len(matrix[0])
for i,j := 0,col -1;i < row && j >= 0; {
if matrix[i][j] == target {
return true
}else if matrix[i][j] < target{
i++
}else{
j--
}
}
return false
}