当前位置:网站首页>Leetcode74. Search 2D Matrix
Leetcode74. Search 2D Matrix
2022-08-01 17:59:00 【Java Full Stack R&D Alliance】
题目传送地址: 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;
}
}
//First use the dichotomy method to determine the target value possible line
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指针和rightWhen the pointer is encountered, it can jump out of the loop
break;
}
left = mid;
}
if (target < matrix[mid][0]) {
if(right==mid){
//如果left指针和rightWhen the pointer is encountered, it can jump out of the loop
break;
}
right = mid;
}
}
row = left;
//Then use the dichotomy method to determine the target value possible columns
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指针和rightWhen the pointer is encountered, it can jump out of the loop
break;
}
left = mid;
}
if (target < matrix[row][mid]) {
if(right==mid){
//如果left指针和rightWhen the pointer is encountered, it can jump out of the loop
break;
}
right = mid;
}
}
return false;
}
}
边栏推荐
猜你喜欢
随机推荐
typora操作手册
阿里云的域名和ip绑定
SQL函数 TO_CHAR(三)
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
Leetcode73. 矩阵置零
Golang协程调度器scheduler怎么使用
【Day_12 0507】查找组成一个偶数最接近的两个素数
MySQL 45 Talk | 09 How to choose common index and unique index?
B002 - 基于嵌入式的老人定位追踪监测仪
创造建材数字转型新视界,中建材如何多边赋能集团业务快速发展
QPalette palette, frame color fill
关于MySql中explain结果filtered的理解
AIOps智能运维的领跑者擎创科技正式入驻InfoQ 写作社区!
自定义注解实现日志打印时屏蔽特定字段不打印
理财产品的月年化收益率怎么算?
QT常用全局宏定义
Leetcode75. 颜色分类
浅谈大数据背景下数据库安全保障体系
GRUB2的零日漏洞补丁现已推出
bat 批示处理详解-2









