当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
Solve the problem that MySQL cannot insert Chinese data
How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.
生物制药产业发展现状和趋势展望
顺序表的简单描述及代码的简单实现
【Day_09 0427】 另类加法
深入分析类加载器
面经汇总-社招-6年
存储日报-数据湖架构权威指南(使用 Iceberg 和 MinIO)
LeaRun.net快速开发动态表单
【Day_08 0426】求最小公倍数
【TDP加码福利】COS用户实践征文月,等你来投稿!!!
解决MySQL插入不了中文数据问题
计算IoU(D2L)
Topology零部件拆解3D可视化解决方案
想做期货,农产品期货怎么炒?波动大么
缓存一致性MESI与内存屏障
QT basic functions, signals, slots
指针和解引用
网上开户佣金万一靠谱吗,网上开户安全吗
B001 - 基于STM32的智能生态鱼缸