Lintcode:搜索二维矩阵
2017-12-06 18:14
405 查看
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每行的第一个数大于上一行的最后一个整数。
样例
考虑下列矩阵:
给出
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;
}
};
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每行的第一个数大于上一行的最后一个整数。
样例
考虑下列矩阵:
[ [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;
}
};
相关文章推荐
- LintCode-28. 搜索二维矩阵
- lintcode-搜索二维矩阵II-38
- LintCode 28. 搜索二维矩阵
- Lintcode 搜索二维矩阵 II
- lintcode 搜索二维矩阵
- LintCode : 搜索二维矩阵
- LintCode Search a 2D matrix 搜索二维矩阵
- lintcode-搜索二维矩阵 java
- LintCode之38 搜索二维矩阵 II
- LintCode: 28. 搜索二维矩阵 Java
- [LintCode]搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- Google/LintCode:M-搜索二维矩阵 II
- Leet Code 74 Search a 2D Matrix - 搜索二维矩阵 - Java
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- lintcode 容易题:Search Insert Position 搜索插入位置
- [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二
- leetCode 74.Search a 2D Matrix(搜索二维矩阵) 解题思路和方法
- 搜索二维矩阵 II
- Lintcode搜索插入位置