Leet Code 74 Search a 2D Matrix

写一个高效的算法,在 m × n 的二维矩阵中搜索一个值。矩阵有以下性质:

每一行从左到右为升序。

每一行的第一个数都比上一行最后一个数大。

例如,有以下矩阵:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

给定 target = 3,返回 true。

思路:二分法,目标值与 (m/2,n/2) 位置的值比较,如果相等则返回true,如果目标值小,则搜索矩阵中小于 (m/2,n/2) 的部分,否则搜索矩阵中大于 (m/2,n/2) 的部分。

1public class Solution { 2 public static boolean searchMatrix(int[][] matrix, int target) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 return false; 5 } 6 return searchMatrix(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, 7 target); 8 } 9 10 private static boolean searchMatrix(int[][] matrix, int top, int left, 11 int bottom, int right, int target) { 12 if (top == bottom && left == right) { 13 return matrix[top][left] == target; 14 } 15 int row = (top + bottom) >> 1; 16 int col = (left + right) >> 1; 17 if (matrix[row][col] < target) { 18 if (row + 1 <= bottom) { 19 if (searchMatrix(matrix, row + 1, left, bottom, col, target)) { 20 return true; 21 } 22 } 23 if (col + 1 <= right) { 24 if (searchMatrix(matrix, row, col + 1, bottom, right, target)) { 25 return true; 26 } 27 } 28 return false; 29 } else if (matrix[row][col] > target) { 30 if (col - 1 >= left) { 31 if (searchMatrix(matrix, top, left, row, col - 1, target)) { 32 return true; 33 } 34 } 35 if (row - 1 >= top) { 36 return searchMatrix(matrix, top, col, row - 1, right, target); 37 } else { 38 return false; 39 } 40 } else { 41 return true; 42 } 43 } 44 45}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

一篇文章带你了解JavaScript日期

日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用

Java修道之路,问鼎巅峰,我辈代码修仙法力齐天

<center<fontcolor00FF7Fsize5face"黑体"代码尽头谁为峰,一见秃头道成空。</font<center<fontcolor00FF00size5face"黑体"编程修真路破折,一步一劫渡飞升。</font众所周知,编程修真有八大境界:1.Javase练气筑基2.数据库结丹3.web前端元婴4.Jav