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

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

题目地址:

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 from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

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

Given target = 3, return true.

既然有序,那毫无疑问,二分查找肯定是跑不了了,首先垂直方向二分查找,确定好target所在的行,然后水平方向二分查找。

public class Search2DMatrix {
public static boolean searchMatrix(int[][] matrix, int target) { if (matrix == null) return false; if (matrix.length == 0) return false; int elemCnt = 0; for (int i = 0; i < matrix.length; i++) { elemCnt += matrix[i].length; } if (elemCnt == 0) return false; if (target < matrix[0][0]) return false; if (target > matrix[matrix.length - 1][matrix[0].length - 1]) return false; int top = 0; int bottom = matrix.length - 1; int midRow = top + (bottom - top) / 2; while (top <= bottom) { if (matrix[midRow][0] == target) { return true; } else if (matrix[midRow][0] > target) { bottom = midRow - 1; midRow = top + (bottom - top) / 2; continue; } else { top = midRow + 1; midRow = top + (bottom - top) / 2; continue; } } if (top < 0) top = 0; if (top > matrix.length - 1) top = matrix.length - 1; if (matrix[top][0] > target) top--; int left = 0; int right = matrix[top].length - 1; int midCol = left + (right - left) / 2; while (left <= right) { if (matrix[top][midCol] == target) { return true; } else if (matrix[top][midCol] > target) { right = midCol - 1; midCol = left + (right - left) / 2; } else { left = midCol + 1; midCol = left + (right - left) / 2; } } return false; } public static void main(String[] args) { int[][] maxtrix = new int[][]{ {
0, 1, 2, 3, 5}, {
6, 8, 9, 10, 11}, {
12, 13, 14, 16, 17}, {
18, 19, 20, 21, 23}, {
24, 26, 27, 28, 29}, {
30, 31, 32, 33, 34}, {
36, 37, 38, 39, 40}, {
42, 44, 45, 46, 47} }; System.out.println(searchMatrix(maxtrix, 41)); return; }}

最后注意一下这种特殊情况的矩阵:{

{}, ...}。

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

你可能感兴趣的文章
动态规划法(六)鸡蛋掉落问题(一)
查看>>
算法数据结构 思维导图学习系列(1)- 数据结构 8种数据结构 数组(Array)链表(Linked List)队列(Queue)栈(Stack)树(Tree)散列表(Hash)堆(Heap)图
查看>>
【机器学习】机器学习系统SysML 阅读表
查看>>
最小费用流 Bellman-Ford与Dijkstra 模板
查看>>
实现高性能纠删码引擎 | 纠删码技术详解(下)
查看>>
scala(1)----windows环境下安装scala以及idea开发环境下配置scala
查看>>
zookeeper(3)---zookeeper API的简单使用(增删改查操作)
查看>>
zookeeper(4)---监听器Watcher
查看>>
mapReduce(3)---入门示例WordCount
查看>>
hbase(3)---shell操作
查看>>
hbase(1)---概述
查看>>
hbase(5)---API示例
查看>>
SSM-CRUD(1)---环境搭建
查看>>
SSM-CRUD(2)---查询
查看>>
SSM-CRUD (3)---查询功能改造
查看>>
Nginx(2)---安装与启动
查看>>
springBoot(5)---整合servlet、Filter、Listener
查看>>
C++ 模板类型参数
查看>>
C++ 非类型模版参数
查看>>
设计模式 依赖倒转原则 & 里氏代换原则
查看>>