当前位置:网站首页>leetcode 240.搜索二维矩阵II 分治思想
leetcode 240.搜索二维矩阵II 分治思想
2022-08-08 18:26:00 【Alkali!】
题目描述
思路
这道题的关键在于得找到特殊位置的起始点,从该起始点,可以分治地去查找待查找地点。
主对角线上左上角和右下角不符合条件,因为
- 左上角的点,其周围的点都比它大,没法找到合适的查找路径
- 右下角的点,其周围的点都比它小,没法找到合适的查找路径
次对角线上左下角和右上角的点更合适,因为
- 左下角的点:往上比它小,往右比它大
- 右上角的点:往左比它小,往下比它大
因此,选择左下角或右上角的点都合适。
代码
选择右上角的点为起点:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size()==0||matrix[0].size()==0) return false;
for(int i=0,j=matrix[0].size()-1;i<matrix.size()&&j>=0;)
{
if(matrix[i][j]==target) return true;
else if(matrix[i][j]>target) j--;
else i++;
}
return false;
}
};
选择左下角的点为起点:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size()==0||matrix[0].size()==0) return false;
for(int i=matrix.size()-1,j=0;j<matrix[0].size()&&i>=0;)
{
if(matrix[i][j]==target) return true;
else if(matrix[i][j]>target) i--;
else j++;
}
return false;
}
};
边栏推荐
猜你喜欢
随机推荐
Why do programmers only close monitor from none computer after work?Look at the answer ~ each big web site
重读GPDB 和 TiDB 论文引发的 HTAP 数据库再思考
Style Design Principles in Open Office XML Format
synApps -- Autosave
/目录 、/home目录 、~目录的区别
mv-lcd初始化
FTP服务初探
面试官:synchronized 和 Lock 的区别是什么?
响应式pbootcms模板建筑装饰类网站
DHCP服务初探
同花顺可以买股票吗?买股票安全吗?
浅谈C语言简单实现二分查找
Numpy函数、模块、类列表
量子力学奇妙之旅-铁磁性来由/双态系统
A Preliminary Study on Pannellum, a Lightweight Panorama Viewer
torchvision.transforms
一些小题22.08.07
Oracle - table
数据压缩和归档(三)、tarfile
Is there any function in MAXCOMPUTE SQL to judge whether the string is a number?