leetcode : 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.

思路很明显是先找可能会在哪一行然后再搜索可能的那一行。因为是有序的所以用二分查找很方便,但是在查找行数的时候是要找第一次小于target的行,由于二分查找在未找到而结束时,start = end + 1,并且end可能向左越界,start可能向右越界。

AC代码:

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        int start = 0, end = matrix.size() - 1;
        while(start <= end){
            int mid = (start + end) >> 1;
            if(target == matrix[mid][0])
                return true;
            if(matrix[mid][0] < target)
                start = mid + 1;
            else
                end = mid - 1;
        }
        if(end < 0)
            return false;
        else
            return searchCol(matrix[end], target);
    }
    bool searchCol(vector<int> &col, int target){
        int start = 0, end = col.size() - 1;
        while(start <= end){
            int mid = (start + end) >> 1;
            if(target == col[mid])
                return true;
            if(col[mid] < target)
                start = mid + 1;
            else
                end = mid - 1;
        }
        return false;
    }
};

 

posted on 2014-11-28 22:39  远近闻名的学渣  阅读(177)  评论(1)    收藏  举报

导航