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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

 

 

解题思路:

这道题可以使用二分法来解答。

因为题目限制,可以先对最后一列进行二分搜索来确定可能会出现在哪一行,也要注意可能出现在最后一列的可能。

确定哪一行后,在对这一行进行二分搜索,确定是否存在。

 

代码:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty() || matrix[0].empty()) return false;
        int m = matrix.size();
        int n = matrix[0].size();
        
        int l = 0, r = m-1;
        while(l < r){
            int mid = l + (r - l)/2;
            if(matrix[mid][n-1] == target) return true;
            else if(matrix[mid][n-1] < target) l = mid+1;
            else r = mid;
        }
        if(matrix[r][n-1] == target) return true;
        int rows = matrix[r][n-1] > target ? r : r+1;
        if(rows == m) return false;
        l = 0, r = n-1;
        while(l < r){
            int mid = l + (r - l)/2;
            if(matrix[rows][mid] == target) return true;
            else if(matrix[rows][mid] < target) l = mid+1;
            else r = mid;
        }
        return matrix[rows][r] == target;
    }
};

 

posted @ 2018-08-10 02:05  妖域大都督  阅读(171)  评论(0编辑  收藏  举报