前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >力扣 - 剑指 Offer 04. 二维数组中的查找

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

作者头像
冬夜先生
修改2021-10-20 10:25:45
1530
修改2021-10-20 10:25:45
举报
文章被收录于专栏:csicocsicocsico

题目#

剑指 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(MN),最坏情况是直到最后一个才找到目标值
  • 空间复杂度:O(1)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(M+N),最坏情况就是遍历一行加上遍历一列
  • 空间复杂度:O(1)O(1)

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目#
  • 思路1#
    • 代码#
      • 复杂度分析#
      • 思路2#
        • 代码#
          • 复杂度分析#
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档