题目要求

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.

分析

一开始写的时候把他拆分成了两个二分查找,先纵向找,再横向找。纵向的二分查找比较复杂,要确定是在某个坐标上,或者在两个坐标之间。

后来找到一个更好的方法,就是把二维数组的坐标转化成一位数组,整体进行二分查找,程序更简单,复杂度也更低了。

Java代码

public boolean searchMatrix(int[][] matrix, int target) {

    if (matrix.length == 0 || matrix[0].length == 0) {
return false;
} int xLength = matrix[0].length;
int min = 0;
int max = matrix[0].length * matrix.length - 1; int x, y, current;
while (min <= max) {
current = (min + max) / 2;
y = current / xLength;
x = current % xLength;
if (matrix[y][x] == target) {
return true;
} else if (target < matrix[y][x]) {
max = current - 1;
} else {
min = current + 1;
}
} return false;
}

最新文章

  1. 【转载】兼容php5,php7的cURL文件上传示例
  2. Ext.NET MVC 配置问题总结
  3. 复旦大学2015--2016学年第二学期高等代数II期末考试情况分析
  4. ARCGIS server没有服务、silverlight不能调试、windows server2008安装时跳出“安装程序无法创建新的系统分区也无法定位现有的系统分区”的解决方案
  5. opengl基础学习专题 (二) 点直线和多边形
  6. D&amp;F学数据结构系列——插入排序
  7. centos coreseek 快速安装
  8. wordpress4.0.1源码学习和摘录--项目设置
  9. Linux下Samba的配置
  10. URL中#(井号)的作用(转)
  11. 写一个python的服务监控程序
  12. API手册(2017)
  13. 安装Linux Mint 17后要做的20件事
  14. The Little Prince-12/11
  15. (原创)如何使用boost.asio写一个简单的通信程序(一)
  16. 软件安装的list(0918)
  17. POJ 1753 bfs+位运算
  18. 一个简单 Go Web MVC 框架实现思路
  19. Maven项目使用阿里云的Maven库
  20. springcloud16---zuul-filter

热门文章

  1. 了解C#文件操作
  2. chrome 浏览器插件开发
  3. C++和C#实现剪切板数据交互
  4. location 符号
  5. Makefile 12——改善编译效率
  6. Dubbo源代码实现三:注册中心Registry
  7. git学习(一):git的版本库在哪儿
  8. C语言 &#183; 完数
  9. pictureBox
  10. linux -- camera shot 拍照功能