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

For example,
Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
Given target = 3, return true.

我的想法是2次二分,先找target所在的行,再找所在的列。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        if (n == 0) return false;
        int m = matrix[0].size();
        if (m == 0) return false;
        vector<int> v;
        for (int i = 0; i < matrix.size(); ++i) {
            v.push_back(matrix[i][0]);
            v.push_back(matrix[i][m-1]);
        }
        int id = lower_bound(v.begin(), v.end(), target) - v.begin();
        //cout << id << endl;
        if (id >= v.size()) return false;
        if (v[id] == target) return  true;
        if (id == 0) return false;
        int t;
        if (id & 1) t = id / 2;
        else t = (id - 1) / 2;
        int x = lower_bound(matrix[t].begin(), matrix[t].end(),target) - matrix[t].begin();
        if (x >= m) return false;
        return matrix[t][x] == target;
    }
};
posted on 2017-10-11 13:33  Beserious  阅读(85)  评论(0编辑  收藏  举报