/**
* Created by lvhao on 2017/8/1.
*
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 Q74Searcha2DMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0)
return false;
int sta = 0;
int fin = matrix.length,mid=0;
boolean res = false;
//二分法查找行
while(sta < fin)
{
mid = (sta + fin)/2;
if (matrix[mid][0] <= target)
{
//如果这一行开头小于等于target且下一行开头大于它(或这一行就是最后一行)
if ((mid + 1) >= matrix.length || matrix[mid+1][0] > target)
break;
else
sta++;
}
else
{
fin--;
}
}
int row = mid;
sta = 0;
fin = matrix[0].length;
//二分法查找数据
while (sta < fin)
{
mid = (sta + fin)/2;
if (matrix[row][mid] == target)
{
res = true;
break;
}
else if (matrix[row][mid] > target)
{
fin--;
}
else
{
sta++;
}
}
return res;
}
}

最新文章

  1. Xcode模拟器启动不了,修复ios模拟器
  2. Unity3D 动态改变地形
  3. Dockerfile完成Hadoop2.6的伪分布式搭建
  4. SQL order by的用法
  5. Elasticsearch安装和使用
  6. 把CheckedListBoxControl设置为单选框
  7. Java多线程——Semaphore信号灯
  8. vbox里面的Ubuntu虚拟机与主机win7之间设置共享文件夹
  9. 【原生js】原生js实现验证码短信发送倒计时
  10. HDU-1995-汉诺塔V
  11. iOS逆向环境以及常用命令行(逆向一)
  12. 01 mysql的安装(windows)
  13. python_crawler,批量下载文件
  14. impdp如何杀掉job
  15. Linux通配符和关机命令
  16. 阿里巴巴开源 Spring Cloud Alibaba,加码微服务生态建设
  17. datetime.timedelta类
  18. 深入 AngularUI Router
  19. TlistView基本使用
  20. STL算法中函数对象和谓词

热门文章

  1. wirshark找不到本地接口
  2. JZOJ2020年8月14日提高组反思
  3. ChromiumWebBrowser flash不能自动播放问题解决方案
  4. [从源码学设计]蚂蚁金服SOFARegistry之消息总线异步处理
  5. day3(Vue组件)
  6. 第二十八章、containers容器类部件QStackedWidget堆叠窗口部件详解
  7. 如何实现OSM地图本地发布并自定义配图
  8. 题解-CF1140E Palindrome-less Arrays
  9. Nginx的安装及相关配置
  10. js常见正则表达式