leetcode 240. Search a 2D Matrix II
2016-03-03 18:47
323 查看
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.
For example,
Consider the following matrix:
[
[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]
]
Given target = 5, return true.
Given target = 20, return false.
accepted
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[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]
]
Given target = 5, return true.
Given target = 20, return false.
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()) return false; if(matrix[0].empty()) return false; if(matrix[0][0]>target||matrix[matrix.size()-1][matrix[0].size()-1]<target) return false; int curX=0,curY=0; bool horizontal=true; while(curX!=matrix[0].size()&&curY!=matrix.size()) { if(horizontal) { while(curX!=matrix[0].size()&&matrix[curY][curX]<target) curX++; if(curX==matrix[0].size()||matrix[curY][curX]>target) { curX--; horizontal=false; curY++; } else return true; } else { while(curY!=matrix.size()&&matrix[curY][curX]<target) curY++; if(curY==matrix.size()||matrix[curY][curX]>target) { if(curY==matrix.size()&&matrix[curY-1][curX]<target) return false; curY--; horizontal=false; curX--; } else return true; } } return false; } };
accepted
相关文章推荐
- Android Cordova 插件开发之创建项目
- canvas 手写毛笔字效果
- mybatis调用orcale存储过程-传入多个参数返回单个字符
- 2016.3.3 软件开发基础
- iOS之九宫格设计(纯代码)
- UIWebView 的属性、方法的具体使用和详解 与JS的交互
- Android Cordova 插件开发之Cordova安装
- Android 异步网络请求导致的程序崩溃
- 算法代码实现之二分法查找,Java实现
- 蓝桥杯历届-古堡算式
- 39.递推练习: 菲波那契数列(2)
- 39.递推练习: 菲波那契数列(2)
- 39.递推练习: 菲波那契数列(2)
- 39.递推练习: 菲波那契数列(2)
- 39.递推练习: 菲波那契数列(2)
- 又一个有趣的mysql死锁测试与源码分析
- HDU 2853 最大匹配&KM模板
- leetcode之2sum
- poj 2187 Beauty Contest 经典题目:凸包+旋转卡壳
- 字符流读写文件