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

本文共 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://bwvfm.baihongyu.com/

你可能感兴趣的文章
程序员修炼之道的提示们(1)
查看>>
变速动画函数封装增加任意一个属性
查看>>
解决弹出的窗口window.open会被浏览器阻止的问题(自定义open方法)
查看>>
可编辑tab选项卡
查看>>
while循环小例
查看>>
eclipse项目打包
查看>>
修改Liunx服务器SSH端口
查看>>
关于SoftReference的使用
查看>>
微笑的眼泪
查看>>
Flex4之DataGrid增删改同步数据库及页面数据示例总结
查看>>
Hadoop平台基本组成
查看>>
java -cp & java jar的区别
查看>>
wpf编写一个简单的PDF转换的程序
查看>>
Win7无线网络显示未连接但可以上网的解决办法
查看>>
浏览器根对象navigator之客户端检测
查看>>
加入一个团队时要弄清楚自己在团队中投入的级别是什么, 别人的期望值是什么. 不要拿着卖白菜的钱, 操那卖白粉的心(转)...
查看>>
expect基础教程
查看>>
ZOJ Problem Set - 3329(概率DP)
查看>>
20款超酷的jQuery插件-随心所欲
查看>>
python urllib2查询数据
查看>>