博客
关于我
【java】74. 搜索二维矩阵---代码优化,时间复杂度接近O(N)!!!
阅读量:325 次
发布时间:2019-03-04

本文共 1154 字,大约阅读时间需要 3 分钟。

为了高效地判断m×n矩阵中是否存在目标值,我们可以利用矩阵的特殊性质:每行有序递增,且每行的第一个数大于上一行的最后一个数。这种结构使得我们可以通过逐行查找和二分查找来优化搜索过程。

方法思路

  • 逐行检查:首先遍历每一行,逐个检查是否存在目标值。
  • 剪枝处理:对于每一行,先检查该行是否有可能包含目标值。如果当前行的第一个数大于目标值或最后一个数小于目标值,则跳过该行。
  • 二分查找:如果该行有可能包含目标值,则在该行中使用二分查找来确定是否存在目标值。
  • 这种方法充分利用了每行有序的特性,减少了不必要的比较,提高了效率。

    解决代码

    public boolean searchMatrix(int[][] matrix, int target) {    int m = matrix.length;    if (m == 0) return false;    int n = matrix[0].length;    for (int i = 0; i < m; i++) {        int[] row = matrix[i];        if (row[0] > target) {            continue;        }        if (row[n - 1] < target) {            continue;        }        int left = 0;        int right = n - 1;        while (left <= right) {            int mid = (left + right) / 2;            if (row[mid] == target) {                return true;            } else if (row[mid] < target) {                left = mid + 1;            } else {                right = mid - 1;            }        }    }    return false;}

    代码解释

    • 遍历每一行:使用一个循环遍历矩阵的每一行。
    • 剪枝处理:对于每一行,首先检查该行的第一个数是否大于目标值或最后一个数是否小于目标值。如果是,则跳过该行。
    • 二分查找:在可能包含目标值的行中,使用二分查找来确定是否存在目标值。如果找到目标值,返回true;否则继续下一行。
    • 返回结果:如果遍历完所有行后都没有找到目标值,返回false。

    这种方法的时间复杂度为O(m log n),能够高效地处理较大的矩阵。

    转载地址:http://tamq.baihongyu.com/

    你可能感兴趣的文章
    NMAP网络扫描工具的安装与使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>