Search a 2D Matrix
2015-09-11 10:41
267 查看
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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
Given target =
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
if(matrix.size() == 0)
{
return false;
}
int i = 0;
int j = matrix[0].size() - 1;
while(1)
{
if(matrix[i][j] == target)
{
return true;
}
if(matrix[i][j] > target)
{
-- j;
}else
{
++ i;
}
if(i >= matrix.size() || j < 0)
{
return false;
}
}
return false;
}
};
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =
3, return
true.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
if(matrix.size() == 0)
{
return false;
}
int i = 0;
int j = matrix[0].size() - 1;
while(1)
{
if(matrix[i][j] == target)
{
return true;
}
if(matrix[i][j] > target)
{
-- j;
}else
{
++ i;
}
if(i >= matrix.size() || j < 0)
{
return false;
}
}
return false;
}
};
相关文章推荐
- URL编程简介
- 【转】Java开源项目源码阅读方法及二次开发方法
- jar随意下
- win8设置默认浏览器,或默认打开方式
- SpringMVC深度探险(一) —— SpringMVC前传
- Android自学历程—手把手教你使用OkHttp(含各种请求方法)
- 腾讯、阿里、华为的岗位薪资情况概述
- 简单JavaSE游戏----扫雷
- JS细节整理
- SSH协议 和 Telnet协议远程登录
- ssh整合!Struts.xml、hibernate与spring整合的applicationContext.xml、web.xml文件的配置!
- SELINUX 导致rsync无法同步文件
- IOS的变量前加extern和static字段
- win8下浏览器性能对比
- 3D Transformations
- 关于javascript中apply()和call()方法的区别
- 使用函数累加数组内数值的和
- HDR和toneMapping
- WebService 理解
- (Google)TextView属性大全(API-16)