当前位置:网站首页>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;
}
};
边栏推荐
- 传音控股:目前公司手机产品暂无明确计划进入中国市场
- Fortinet new cloud native protection products launched amazon cloud platform of science and technology
- SUSECON 北京议程上新丨8月16日相聚望京凯悦
- Style Design Principles in Open Office XML Format
- 行政区划代码(道路要素)
- echart 股票数据分析 开发备忘录
- uniapp parent component uses prop to pass asynchronous data to child components
- LabVIEW报错“仪器IO助手未正确安装”
- 数据压缩和归档(二)、zipfile
- 2021年9月电子学会图形化一级编程题解析含答案:小狗进圈
猜你喜欢

uniapp父组件使用prop将异步的数据传给子组件

/目录 、/home目录 、~目录的区别

TensorFlow学习记录(七):生成对抗网络

Learn about layered architecture & SOA architecture together

搭建企业级数据治理体系指南

Performance optimization | CPU power management from the perspective of ping delay

Fortinet全新云原生保护产品上线亚马逊云科技平台

Laravel 5.8 Notes

echart 股票数据分析 开发备忘录

Geometric g6 will carry harmonyos system, a comprehensive upgrade competitiveness of products
随机推荐
行政区划代码(道路要素)
Architecture Design Fundamentals
请问在MAXCOMPUTE SQL 里有没有函数判断string 是否为数字?
/目录 、/home目录 、~目录的区别
hdu1042 N!(大数)
ptorch
“非洲之王”传音答复投资者提问:手机产品暂无计划进入中国
PG 之 huge page
面试官:Redis 大 key 要如何处理?
16. Learn Lua file I/O together
How to add F4 Value Help trial version to the input parameters of the report in the ABAP report
Is there any function in MAXCOMPUTE SQL to judge whether the string is a number?
栈指针&& 帧指针详解
SSH协议抓包-工具Wireshark
建设必要的是什么意思
FTP服务初探
A Preliminary Study on Pannellum, a Lightweight Panorama Viewer
JVM内存模型和结构详解(五大模型图解)
PX4模块设计之十八:Logger模块
We want to replace the RDS database and upgrade from sqlserver 2016 web to 2017 enterprise cluster version, with expert consultation


