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

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

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

难度:medium

题目:设计高效算法在矩阵中搜索给定的值。矩阵特性如下:每行元素从左到右递增,每列元素从上到下递增。

思路:在第一个行中找出首元素大于target的列,在第一个列中找出首元素大于target的行。然后对每行进行二叉搜索。

Runtime: 6 ms, faster than 97.21% of Java online submissions for Search a 2D Matrix II.

Memory Usage: 46.6 MB, less than 23.14% of Java online submissions for Search a 2D Matrix II.

class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if(matrix.length == 0 || matrix[0].length == 0) {            return false;        }                int m = matrix.length, n = matrix[0].length;        int row = 0, column = 0;        for (; column < n; column++) {            if (matrix[0][column] > target) {                break;            }        }        for (; row < m; row++) {            if (matrix[row][0] > target) {                break;            }        }                for (int i = 0; i < row; i++) {            if (Arrays.binarySearch(matrix[i], 0, column, target) >= 0) {                return true;            }        }        return false;    }}

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

你可能感兴趣的文章
阅读笔记《构建之法》一
查看>>
Android 虚拟机 程序安装目录
查看>>
深入学习Hive应用场景及架构原理
查看>>
07-01 Java 封装
查看>>
HDU_1143_tri tiling
查看>>
codeforces_1075_C. The Tower is Going Home
查看>>
使用BBED模拟Oracle数据库坏块
查看>>
C# 关于XML的简单操作实例
查看>>
ggplot2:画世界地图和中国地图 合并数据 增添信息 标记
查看>>
VertexBuffer渲染次序
查看>>
div高度自适应
查看>>
python中使用 xpath
查看>>
集中管理:领导者,不能不考虑的几件事之—— 拿什么辅助你,我的决策?(一)...
查看>>
四、物理优化(6)数据库引擎优化顾问
查看>>
我的友情链接
查看>>
关于VirtualBox虚拟机安装GhostXP出现蓝屏proce***.sys 的解决办法
查看>>
浅谈 C#委托
查看>>
Atitit.跨语言反射api 兼容性提升与增强 java c#。Net php js
查看>>
【Thread】多线程的异常处理?
查看>>
H.264 CODEC
查看>>