LeetCode Search a 2D Matrix

题目链接:https://oj.leetcode.com/problems/search-a-2d-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<vector<int> > &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<m&&y>=0&&y<n)
        {
        	if(matrix[x][y]==target) return true;
        	else if(matrix[x][y]>target) y--;
        	else x++;
        }
        return false;
    }
};


posted @ 2017-05-29 08:02  yxysuanfa  阅读(121)  评论(0编辑  收藏  举报