当前位置:网站首页>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;
}
}
边栏推荐
- 打开微信客服
- 半自动化爬虫-爬取一个网站的内容及回复
- When custom annotations implement log printing, specific fields are blocked from printing
- 力扣每日一题-第45天-697. 数组的度
- 深圳市商务局2022年度中央资金(跨境电子商务企业市场开拓扶持事项)申报指南
- QT_QDialog 对话框
- The anxiety of the post-90s was cured by the vegetable market
- 生物制药产业发展现状和趋势展望
- 广汽埃安“弹匣电池”,四大核心技术,出行安全保障
- ROS2系列知识(5):【参数】如何管理?
猜你喜欢

hcip第九天

阿里云的域名和ip绑定

【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)

素域和扩域

史上最全的Redis基础+进阶项目实战总结笔记

QT basic functions, signals, slots

Topology零部件拆解3D可视化解决方案

8月微软技术课程,欢迎参与

Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?

RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
随机推荐
实现mnist手写数字识别
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
Topology Parts Disassembly 3D Visualization Solution
解决MySQL插入不了中文数据问题
后台管理系统的权限思路
关系运算符和if,else语句
SQL的ROUND函数用法及其实例
B011 - 基于51的多功能指纹智能锁
百度网盘下载速度提升100倍
Shell nl命令详解(显示行号、读取文件)
快速抽取resnet_v2_152中间的特征层
基于BiGRU和GAN的数据生成方法
gtk显示4通道rgba图像
我在启牛开户安全吗?谁能告诉我开不靠谱?
ROS2系列知识(6):Action服务概念
2022.08月--pushmall推贴共享电商更新与开发计划
【报错】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat‘)
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
创造建材数字转型新视界,中建材如何多边赋能集团业务快速发展
浅谈大数据背景下数据库安全保障体系