leetcode[74]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.

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        if(matrix.empty())return false;
        int row=matrix.size();
        if(matrix[0].empty())return false;
        int col=matrix[0].size();
        int left=0,right=row*col-1;
        while(left<=right)
        {
            int mid=(left+right)/2;
            int temp=matrix[mid/col][mid%col];
            if(temp==target)return true;
            else if(temp<target)left=mid+1;
            else right=mid-1;
        }
        return false;
    }
/**
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        if(matrix.empty())return false;
        int row=matrix.size();
        if(matrix[0].empty())return false;
        int col=matrix[0].size();
        int i=0,j=col-1;
        while(i<row&&j>=0)
        {
            if(matrix[i][j]==target)return true;
            else if(matrix[i][j]<target)i++;
            else j--;
        }
        return false;
    }
*/
};

 

posted @ 2015-02-09 14:20  Vae永Silence  阅读(152)  评论(0编辑  收藏  举报