Leetcode Search a 2D Matrix

OpenSoucre發表於2014-06-26

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(logm)+O(logn)

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        if(target < matrix[0][0] || target >matrix[n-1][m-1]) return false;
        int left = 0 , right = n-1, targetRow = 0;
        //縱向二分查詢
        while(left <= right){
            int mid = (left+right)>>1;
            if(matrix[mid][0] > target ) right = mid-1;
            else if(matrix[mid][0] < target) left = mid+1;
            else break;
        }
        if(left>right) targetRow =right;
        else return true;
        //橫向二分查詢
        left = 0;right = m-1;
        while(left <= right){
            int mid = (left+right)>>1;
            if(matrix[targetRow][mid] > target) right = mid-1;
            else if(matrix[targetRow][mid] < target) left = mid+1;
            else break;
        }
        if(left <=right ) return true;
        else return false;
    }
};
先縱向後橫向查詢

方法二,直接二分查詢

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        if(target < matrix[0][0] || target >matrix[n-1][m-1]) return false;
        int left = 0 , right = n*m-1;
        while(left<=right){
            int mid = (left+right)>>1;
            if(matrix[mid/m][mid%m] > target) right = mid-1;
            else if(matrix[mid/m][mid%m] <  target) left = mid+1;
            else return true;
        }
        return false;
    }
};
整體查詢

 

 

相關文章