74. Search a 2D Matrix (Graph; Divide-and-Conquer)

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) {
        int start = 0, end = matrix.size()-1;
        int mid;
        int lineNum;
        while(start<=end){
            mid = start + ((end-start)>>1);
            if(matrix[mid][0]<target){
                start = mid+1;
            }
            else if(matrix[mid][0]>target){
                end = mid-1;
            }
            else return true;
        }
        if(end < 0) return false;
        lineNum = end;
        start = 0;
        end = matrix[0].size()-1;
        while(start<=end){
            mid = start + ((end-start)>>1);
            
            if(matrix[lineNum][mid]<target){
                start = mid+1;
            }
            else if(matrix[lineNum][mid]>target){
                end = mid-1;
                
            }
            else return true;
        }
        return false;
    }
};

 

posted on 2015-10-04 15:51  joannae  阅读(159)  评论(0编辑  收藏  举报

导航