lintcode刷题——搜索二维矩阵
来源:互联网 发布:怎样做网络推广话术 编辑:程序博客网 时间:2024/06/09 19:28
lintcode刷题之搜索二维矩阵,题目如下所示:
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
考虑下列矩阵:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
给出 target = 3
,返回 true
1、由于每一个vector里面都是有序的,所以首先找到待搜索元素在哪一个vector里面;
2、找到待搜索元素所在的vector之后再对该行数据进行二分法查找;
具体的c++代码如下:
class Solution {
public:
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
bool erfenchazhao(vector<int>&v,int target)
{
if(v.size()==0)
{
return false;
}
int i,j;
i=0,j=v.size()-1;
int temp=(i+j)/2;
while(i<=j)
{
if(v[temp]<target)
{
i=temp+1;
temp=(i+j)/2;
}
else if(v[temp]>target)
{
j=temp-1;
temp=(i+j)/2;
}
else
{
return true;
}
}
return false;
}
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// write your code here
int row=matrix.size();
if(row==0)
{
return false;
}
int col=matrix[0].size();
int t;
int i,j;
for(i=0;i<row;i++)
{
if(target<matrix[i][0])
{
t=i;
break;
}
}
if(i==row)
{
return erfenchazhao(matrix[row-1],target);
}
if(t==0)
{
return false;
}
else
{
return erfenchazhao(matrix[t-1],target);
}
}
};
- lintcode刷题——搜索二维矩阵
- 搜索二维矩阵——LintCode
- lintcode ---- 搜索二维矩阵
- lintcode ----搜索二维矩阵
- 【LintCode】搜索二维矩阵
- lintcode,搜索二维矩阵
- LintCode : 搜索二维矩阵
- Lintcode:搜索二维矩阵
- LintCode:搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- Lintcode 搜索二维矩阵 II
- LintCode 28 搜索二维矩阵
- [LintCode]28.搜索二维矩阵
- lintcode---搜索二维矩阵Ⅱ
- lintcode-搜索二维矩阵II-38
- [LintCode]搜索二维矩阵 II
- Cloudkitty Data Flow(Newton版)
- 市场研究中的数据分析知识整理 (七)-结构方程模型
- git生成patch,应用到rpmbuild 打补丁
- 关于Activity
- Maven 构建配置文件
- lintcode刷题——搜索二维矩阵
- 矩阵构造+矩阵快速幂-HDU5950
- 用栈实现队列
- 单元测试,在控制台输入测试值。
- 20款优秀的免费代码编辑器
- 网络判断(广播)
- SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库
- 学习记录
- 物体检测 faster rcnn