设为首页 加入收藏

TOP

LeetCode Search a 2D Matrix
2015-07-24 06:51:49 来源: 作者: 【 】 浏览:55
Tags:LeetCode Search Matrix

?

?

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:

    [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    Given target = 3, return true.


    由于这个矩阵是有序的,我们可以从右上角开始进行比较,若比右上角大,则肯定在下一行,否则就在本行中,时间复杂度O(m+n)

    ?

    当然也可以用二分来做,同样从最右边那一列开始看,先二分出是在哪一行,然后再二分出是在哪一列时间复杂度 O(logn+logm)

    ?

    下面给出O(m+n)的代码

    ?

    ?

    class Solution {
    public:
        bool searchMatrix(vector
        
          > &matrix, int target) {
            int m=matrix.size();
            int n=matrix[0].size();
            if(matrix.empty()||matrix[0].empty()) return false;
            int x=0,y=n-1;
            while(x>=0&&x
         
          =0&&y
          
           target) y--; else x++; } return false; } }; 
          
         
        


    ?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇并行编程之条件变量(posix condi.. 下一篇Design Pattern Singleton 单一模..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: