[leetcode] Add to List 74. Search a 2D Matrix
2024-09-08 02:57:58
/**
* 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;
}
}
最新文章
- Xcode模拟器启动不了,修复ios模拟器
- Unity3D 动态改变地形
- Dockerfile完成Hadoop2.6的伪分布式搭建
- SQL order by的用法
- Elasticsearch安装和使用
- 把CheckedListBoxControl设置为单选框
- Java多线程——Semaphore信号灯
- vbox里面的Ubuntu虚拟机与主机win7之间设置共享文件夹
- 【原生js】原生js实现验证码短信发送倒计时
- HDU-1995-汉诺塔V
- iOS逆向环境以及常用命令行(逆向一)
- 01 mysql的安装(windows)
- python_crawler,批量下载文件
- impdp如何杀掉job
- Linux通配符和关机命令
- 阿里巴巴开源 Spring Cloud Alibaba,加码微服务生态建设
- datetime.timedelta类
- 深入 AngularUI Router
- TlistView基本使用
- STL算法中函数对象和谓词