74. Search a 2D Matrix

来源:互联网 发布:网络语飙车是什么意思 编辑:程序博客网 时间:2024/05/21 11:05

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() || matrix[0].empty()) return false;        if (target < matrix[0][0]) return false;        int row = matrix.size(), col = matrix[0].size();        int r = 0;        for (int i = 0; i < row - 1; i++) {            if (matrix[i][0] <= target && matrix[i+1][0] > target) {                r = i;                break;            }        }        if (target >= matrix[row-1][0]) r = row - 1;        int begin = 0, end = col - 1;        int mid = (begin + end) / 2;        while (begin <= end) {            if (target == matrix[r][mid]) return true;            if (target < matrix[r][mid]) end = mid - 1;            else if (target > matrix[r][mid]) begin = mid + 1;            mid = (begin + end) / 2;        }        return false;    }};
原创粉丝点击