博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Search a 2D Matrix II
阅读量:6879 次
发布时间:2019-06-26

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

Description:

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

 

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

 

For example,

Consider the following 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]]

Given target = 5, return true.

Given target = 20, return false.

首先想到的就是遍历整个矩阵,时间复杂度是O(m*n),肯定是Timeout

public class Solution {    public boolean searchMatrix(int[][] matrix, int target) {                for(int i=0; i

然后在优化的话就想到了二分。对每一行进行二分。时间复杂度是O(n*logm),还是Timeout,二分用的越多时间复杂度就越高,所以行列都二分(有点递归分治的意思)更会Timeout。

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

这么看来时间复杂度必须在线性的基础上才行。观察一下矩阵不难发现把矩阵逆时针旋转45度类似一棵二叉查找树。所以就可以模仿二叉查找树的方法来做了。

这样的话时间复杂度就是O(m + n);AC。

public class Solution {            public boolean searchMatrix(int[][] matrix, int target) {                if(matrix.length==0 || matrix[0].length==0) {            return false;        }                int i = 0, j = matrix[0].length - 1;                while(i < matrix.length && j >= 0) {            int cur = matrix[i][j];            if(cur == target) {                return true;            }            else if(cur < target) {                i ++;            }            else {                j --;            }                    }        return false;            }    }

 

转载于:https://www.cnblogs.com/wxisme/p/4850273.html

你可能感兴趣的文章
实现JSP页面
查看>>
【iOS-cocos2d-X 游戏开发之十】自定义各类模版&触屏事件讲解!
查看>>
SCN浅析
查看>>
吐槽“云计算”
查看>>
使用Cocos2d-x-3.0游戏引擎编写一个塔防游戏1
查看>>
Exchange 2010和Exchange 2016共存部署-4:Exchange2016部署先决条件
查看>>
VSTO之旅系列(二):创建Excel解决方案
查看>>
SQL Server 2012笔记分享-3:版本对比
查看>>
mcollective插件(shell plugins)功能在Linux系统上无所不能
查看>>
SCVMM2012部署之三:安装VMM自助服务门户
查看>>
白鳝老师受邀亲临ITPUB社区与网友交流DBA思想,感悟Oracle数据本质
查看>>
《 软件性能测试与LoadRunner实战教程》喜马拉雅有声图书上线
查看>>
这些年我是如何在知乎安稳引流不被封号的
查看>>
第6章 配置邮箱高可用
查看>>
proxmox集群节点崩溃处理
查看>>
WSUS in Windows Server 2012(update)
查看>>
MySQL5.7在线开启/关闭GTID
查看>>
浅谈Oracle执行计划
查看>>
VMware ESXi5.5主机无法挂载RHEL6.5 NFS存储
查看>>
VMware安装Oracle Enterprise Linux 5.8 x86_64
查看>>