[240]Search a 2D Matrix II
2015-10-26 20:59
441 查看
【题目描述】
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:
Given target =
Given target =
【思路】
如果从第一个元素开始实现比较麻烦,转换思路,从右上角的元素开始,发现不管哪个元素其左边的元素都比它小,下边的元素都比它大,如果target大于该元素,则搜索其下边的元素,如果小于则搜索其左边的元素。
【代码】
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m=matrix.size();
int n=matrix[0].size();
int row=0;
int col=n-1;
while(row<=m-1&&col>=0){
if(matrix[row][col]>target) col--;
else if(matrix[row][col]<target) row++;
else if(matrix[row][col]==target) return true;
}
return false;
}
};
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.
【思路】
如果从第一个元素开始实现比较麻烦,转换思路,从右上角的元素开始,发现不管哪个元素其左边的元素都比它小,下边的元素都比它大,如果target大于该元素,则搜索其下边的元素,如果小于则搜索其左边的元素。
【代码】
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m=matrix.size();
int n=matrix[0].size();
int row=0;
int col=n-1;
while(row<=m-1&&col>=0){
if(matrix[row][col]>target) col--;
else if(matrix[row][col]<target) row++;
else if(matrix[row][col]==target) return true;
}
return false;
}
};
相关文章推荐
- hdu 4605 Magic Ball Game(可持久化笛卡尔树)
- 关于iphone accessory的理解
- HDU-2159(FATE)
- 设计模式------工厂方法模式
- hibernate.hbm2ddl.auto配置详解
- 论架构师的自我修养
- 第一次驱动hello
- 机器学习中防止过拟合的处理方法
- Could not load file or assembly 'XXX' or one of its dependencies
- C++:多重继承
- oracle dba 使用mysql 时的痛点--待吐槽
- Android 理解生命周期最好例子—按home暂停音乐播放,跳转暂停
- 对称矩阵的压缩存储及基本运算(2)
- VS2013在文件中查找时无法显示查找结果
- 76 Minimum Window Substring
- 天声人語 20151026 「政治的」なものの忌避
- nginx之反向代理
- socket网络编程复习笔记(三):套接字描述符背后的秘密
- window 对象
- 使用正则表达式来验证日期格式是否为XX/XX/XXXX