当前位置:网站首页>Leetcode74. 搜索二维矩阵
Leetcode74. 搜索二维矩阵
2022-08-01 17:54:00 【Java全栈研发大联盟】
题目传送地址: https://leetcode.cn/problems/search-a-2d-matrix/
运行效率
代码如下:
class Solution {
public static boolean searchMatrix(int[][] matrix, int target) {
int row; //target所在的行
//处理边界情况
if (target > matrix[matrix.length - 1][0]) {
if (target > matrix[matrix.length - 1][matrix[0].length - 1]) {
return false;
} else {
row = matrix.length - 1;
}
}
//先用二分法确定目标值 可能所在的行
int left = 0;
int right = matrix.length;
while (left != right) {
int mid = (left + right) / 2;
if (target == matrix[mid][0]) {
return true;
}
if (target > matrix[mid][0]) {
if(left==mid){
//如果left指针和right指针遇到了就可以跳出循环
break;
}
left = mid;
}
if (target < matrix[mid][0]) {
if(right==mid){
//如果left指针和right指针遇到了就可以跳出循环
break;
}
right = mid;
}
}
row = left;
//再用二分法确定目标值 可能所在的列
left = 0;
right = matrix[0].length;
while (left != right) {
int mid = (left + right) / 2;
if (target == matrix[row][mid]) {
return true;
}
if (target > matrix[row][mid]) {
if(left==mid){
//如果left指针和right指针遇到了就可以跳出循环
break;
}
left = mid;
}
if (target < matrix[row][mid]) {
if(right==mid){
//如果left指针和right指针遇到了就可以跳出循环
break;
}
right = mid;
}
}
return false;
}
}
边栏推荐
- 浅谈游戏音效测试点
- 快速抽取resnet_v2_152中间的特征层
- ROS2系列知识(7):用rqt_console查看日志logs
- BITS Pilani|SAC-AP:基于 Soft Actor Critic 的深度强化学习用于警报优先级
- opencv语法Mat类型总结
- C language theory--a solid foundation for the written test and interview
- EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
- 棕榈油罐区数字化转型
- 广汽埃安“弹匣电池”,四大核心技术,出行安全保障
- 统信软件、龙芯中科等四家企业共同发布《数字办公安全创新方案》
猜你喜欢
随机推荐
B011 - 基于51的多功能指纹智能锁
QT_Event class
程序员架构修炼之道:如何设计“易理解”的系统架构?
创造建材数字转型新视界,中建材如何多边赋能集团业务快速发展
Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
QT_QThread线程
XAML WPF item groupBox control
When custom annotations implement log printing, specific fields are blocked from printing
QPalette调色板、框架色彩填充
QT_事件类
【R语言】对图片进行裁剪 图片批量裁剪
【Day_08 0426】两种排序方法
史上最全的Redis基础+进阶项目实战总结笔记
分布式消息队列平滑迁移技术实战
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
SQL函数 TO_CHAR(一)
QT_QDialog 对话框
Shell nl命令详解(显示行号、读取文件)
数字化采购管理系统开发:精细化采购业务流程管理,赋能企业实现“阳光采购”
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践









