您的位置:首页 > 其它

Lintcode:搜索二维矩阵

2017-12-06 18:14 405 查看
写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每行的第一个数大于上一行的最后一个整数。

样例

考虑下列矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

给出 
target = 3
,返回 
true


python:

class Solution:
"""
@param: matrix: matrix, a list of lists of integers
@param: target: An integer
@return: a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if matrix == None:
return False
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j] == target:
return True
return False

C++:

class Solution {
public:
/*
* @param matrix: matrix, a list of lists of integers
* @param target: An integer
* @return: a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
// write your code here
int m = matrix.size();
if (m == 0)
return false;
int n = matrix[0].size();
if (n == 0)
return false;
for (int i = 0; i < m;i++)
{
for(int j = 0;j < n;j++)
{
if (matrix[i][j] == target)
return true;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: