Lintcode:搜索二维矩阵

来源:互联网 发布:出租车发票打印机软件 编辑:程序博客网 时间:2024/05/29 16:10

写出一个高效的算法来搜索 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;    }};


原创粉丝点击