LeetCode OJ:Search a 2D Matrix II(搜寻二维矩阵)
2024-08-30 17:11:37
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
这题一开始想用从左到右,再上到下的方法去实现,但是不行,后来看了别人的实现,应该使用的是先取右上的元素与target进行比较,如果大于target的话那么这一列都不会存在target,小于的话那么改行都不会存在该元素,从而进行下一步的搜寻,代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size() || !matrix[].size())
return false;
int rowCount = matrix.size();
int colCount = matrix[].size();
for(int i = , j = colCount - ; i < rowCount && j >= ; ){
if(matrix[i][j] == target) return true;
else if(matrix[i][j] > target)
j--;
else
i++;
}
return false;
}
};
最新文章
- 物联网框架ServerSuperIO(SSIO)更新、以及增加宿主程序和配置工具,详细介绍
- Django缓存系统设置
- 20145227&;20145201 《信息安全系统设计基础》实验五
- VB调用sendinput API
- 仿SGI STL的traits技法
- HDOJ 4497 GCD and LCM
- 什么是Angular? 我们为什么要学习它?
- TI CC2541的串口输出.
- HDU 4704
- 戏(细)说Executor框架线程池任务执行全过程(下)
- python学习之旅:array 转 list
- HDU 3909 DLX
- js去掉最后一个字符
- vue填坑指南之模板的使用
- linux系统docker版本升级或安装
- Glass Dragon
- linux中查看http各种状态数量
- 帝国移动pc站文章
- ganglia问题汇总
- SQL Fundamentals: 子查询 || 分析函数(PARTITION BY,ORDER BY, WINDOWING)
热门文章
- maven 介绍(一)
- javaee加密部署,tomcat使用自己的classloader解密
- Python3.x:Selenium+PhantomJS爬取带Ajax、Js的网页
- Helloworld.JaVa 第一次编程
- ubuntu 12.04网络设置
- [翻译]小提示:使用figure和figcaption元素的正确方式
- SpringBoot 简单集成ActiveMQ
- 混合开发的大趋势之一React Native与Android联调
- Shell学习小结 - 深入认识变量
- NuGet version