Loading

力扣 - 剑指 Offer 04. 二维数组中的查找

题目

剑指 Offer 04. 二维数组中的查找

思路1

  • 暴力遍历寻找

代码

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length, columns = matrix[0].length;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }
        return false;
    }
}

复杂度分析

  • 时间复杂度:\(O(MN)\),最坏情况是直到最后一个才找到目标值
  • 空间复杂度:\(O(1)\)

思路2

  • 从右上角或者左下角开始匹配,我是从右上角开始的:如果target小于当前值,则列值往前移动一列;如果大于当前值,则行向下移动一行。如果直到左下角还没有找到target的话,说明不在该二维数组中
  • 注意:不能从左上角或者右下角开始

代码

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        boolean res = false;

        if (matrix.length != 0 && matrix[0].length != 0) {
            int row = 0;
            int col = matrix[0].length-1;
            while (row <= matrix.length-1 && col >= 0) {
                if (target < matrix[row][col]) {
                    col--;
                } else if (target > matrix[row][col]) {
                    row++;
                } else {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }
}

复杂度分析

  • 时间复杂度:\(O(M+N)\),最坏情况就是遍历一行加上遍历一列
  • 空间复杂度:\(O(1)\)
posted @ 2021-10-17 21:42  linzeliang  阅读(32)  评论(0编辑  收藏  举报