package com.heu.wsq.leetcode.inoffer;
/**
* 剑指 Offer 04. 二维数组中的查找
* @author wsq
* @date 2021/5/27
* 在一个 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。
*
* 链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
*/
public class FindNumberIn2DArray {
/**
* 通过分析数组元素值的分布特征:
* 1. 每一行元素是递增的
* 2. 每一列元素也是递增的
* 因此我们需要找到一个位置,在该位置,它有减少和增加两种选择,这样的位置可以选择左下角和右上角
* 这里我们选择右上角作为起点进行遍历
* @param matrix
* @param target
* @return
*/
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int m = matrix.length, n = matrix[0].length;
int i = 0, j = n-1;
while(i < m && j >= 0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
i++;
}else {
j--;
}
}
return false;
}
}
剑指 Offer 04. 二维数组中的查找
最新推荐文章于 2025-06-15 22:26:56 发布