Skip to content

04.二维数组中的查找

  • 暴力求解,全部遍历一次
  • 二分查找
    • 由于每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
    • 从二维数组的右上角开始查找。 如果当前元素等于目标值,则返回 true。如果当前元素大于目标值,则移到左边一列。如果当前元素小于目标值,则移到下边一行
class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        int i = 0, j = matrix[0].length - 1;
        while(i < matrix.length && j >= 0){
            if(target == matrix[i][j]){
                return true;
            }else if(matrix[i][j] > target){
                j--;
            }else{
                i++;
            }
        }
        return false;
    }
}