当前位置:网站首页>LeetCode Brushing Diary: 74. Searching 2D Matrix
LeetCode Brushing Diary: 74. Searching 2D Matrix
2022-08-02 01:55:00 【light [email protected]】
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性:
每行中的整数从左到右按升序排列.
每行的第一个整数大于前一行的最后一个整数.
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
思路:
因为是有序的,So first arrange the last number of each line to compare with the target,Find out if the target is in the range of the current row,不在,then loop to the next line,直到找到为止,找到当前行,Then use a binary search algorithm to find if there is a target in that row.
题解:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int x = 0;
for (int i = 0; i < m; i++) {
if(matrix[i][n-1] >= target){
x = i;
break;
}
}
int start = 0, end = n-1;
while (start <= end){
int mid = (start + end)/2;
if(matrix[x][mid] == target){
return true;
}else if(matrix[x][mid] > target){
end = mid - 1;
}else {
start = mid + 1;
}
}
return false;
}
}
版权声明
本文为[light [email protected]~no trace]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020144011619.html
边栏推荐
猜你喜欢

Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion

Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program

去经营企业吧

Day116.尚医通:预约挂号详情 ※

Basic use of typescript34-class

垃圾回收器CMS和G1

Pcie the inbound and outbound

传统企业数字化转型需要经过几个阶段?

Flink_CDC construction and simple use

手写一个博客平台~第三天
随机推荐
『网易实习』周记(一)
雇用WordPress开发人员:4个实用的方法
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
手写博客平台~第二天
typescript32-ts中的typeof
传统企业数字化转型需要经过几个阶段?
Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
MySQL优化策略
力扣 1374. 生成每种字符都是奇数个的字符串
Day116. Shangyitong: Details of appointment registration ※
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
Image fusion based on weighted 】 and pyramid image fusion with matlab code
Typescript31 - any type
Oracle data to mysql FlinkSQL CDC to achieve synchronization
Byte taught me a hard lesson: When a crisis comes, you don't even have time to prepare...
Newton's theorem and related corollaries
飞桨助力航天宏图PIE-Engine地球科学引擎构建
一本适合职场新人的好书