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

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

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.

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.

 

观察到,左下角的数字,向上递减,向右递增,可以从左下角开始查找,循环成立条件是数组下标不越界。如果 当前数 < target,向右查找;如果 当前数 < target,向上查找。

time: O(M+N), space: O(1)

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

 

转载于:https://www.cnblogs.com/fatttcat/p/10068895.html

你可能感兴趣的文章
[C++再学习系列] 引用和指针
查看>>
未能加载文件或程序集“********”或它的某一个依赖项。试图加载格式不正确的程序。...
查看>>
bootstrap4-图像
查看>>
Centos7 MariaDB10.1.22编译安装
查看>>
路由器配置基础(中)
查看>>
/etc/sudoers的配置
查看>>
菜鸟学Linux 第075篇笔记 mysql事务,视图
查看>>
Mysql + PHP
查看>>
jetty9请求form表单太小限制
查看>>
linux服务器优化1.0版
查看>>
从oracle到mysql,主从到分库,一个普通项目数据库架构的变迁
查看>>
ASP.NET 4.0请求验证报错 从客户端...中检测到有潜在危险的 Request.Form 值
查看>>
ASM
查看>>
mysql常用操作
查看>>
unit 9 文档练习
查看>>
PHP代码优化的40条建议
查看>>
Crontab的用法
查看>>
搭建 LNMP+WordPress 环境
查看>>
Redisson官方文档 - 7. 分布式集合
查看>>
Centos6.7_KVM安装配置使用
查看>>