当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
3D角色建模师和3D角色动画师哪个更有前景?哪个更适合小白入门?
MogDB学习笔记-从0开始
面经刺客 | 关于——字节飞书基础架构产品 日常实习面经
Nioke 2022 Summer Multi-School 6 B Eezie and Pie (Difference on the tree + multiplication to find the kth ancestor board)
传音控股:目前公司手机产品暂无明确计划进入中国市场
性能优化|从ping延时看CPU电源管理
架构设计基本原则
vue项目打包后的网页缓存问题
Azure Neural TTS continues to be updated to help enterprises develop small language markets
Learn about layered architecture & SOA architecture together
随机推荐
422B测试成功
Style Design Principles in Open Office XML Format
21天学习挑战赛——机器学习02
uniapp父组件使用prop将异步的数据传给子组件
01、前言
Vue program of web cache problem after packaging
hdu1042 N! (large number)
A Preliminary Study on Pannellum, a Lightweight Panorama Viewer
OpenInfra Days China 2022即将开启,与 openEuler 共话开源技术
【761. 特殊的二进制序列】
Go-Excelize API源码阅读(四)——Save()
uva1468
synApps -- Autosave
【wpf】Bingding的方向和触发的时机
2022年6月电子学会考级试卷真题解析(含答案和所有文档下载)
面试突击:输入URL之后会执行什么流程?
浅谈C语言简单实现二分查找
Redis Server启动过程
Nioke 2022 Summer Multi-School 6 B Eezie and Pie (Difference on the tree + multiplication to find the kth ancestor board)
几何g6将搭载harmonyos系统,产品竞争力全面升级