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;
}
};

最新文章

  1. 物联网框架ServerSuperIO(SSIO)更新、以及增加宿主程序和配置工具,详细介绍
  2. Django缓存系统设置
  3. 20145227&amp;20145201 《信息安全系统设计基础》实验五
  4. VB调用sendinput API
  5. 仿SGI STL的traits技法
  6. HDOJ 4497 GCD and LCM
  7. 什么是Angular? 我们为什么要学习它?
  8. TI CC2541的串口输出.
  9. HDU 4704
  10. 戏(细)说Executor框架线程池任务执行全过程(下)
  11. python学习之旅:array 转 list
  12. HDU 3909 DLX
  13. js去掉最后一个字符
  14. vue填坑指南之模板的使用
  15. linux系统docker版本升级或安装
  16. Glass Dragon
  17. linux中查看http各种状态数量
  18. 帝国移动pc站文章
  19. ganglia问题汇总
  20. SQL Fundamentals: 子查询 || 分析函数(PARTITION BY,ORDER BY, WINDOWING)

热门文章

  1. maven 介绍(一)
  2. javaee加密部署,tomcat使用自己的classloader解密
  3. Python3.x:Selenium+PhantomJS爬取带Ajax、Js的网页
  4. Helloworld.JaVa 第一次编程
  5. ubuntu 12.04网络设置
  6. [翻译]小提示:使用figure和figcaption元素的正确方式
  7. SpringBoot 简单集成ActiveMQ
  8. 混合开发的大趋势之一React Native与Android联调
  9. Shell学习小结 - 深入认识变量
  10. NuGet version