[LeetCode-74] Search a 2D Matrix
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
.
水题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int row_cnt = matrix.size(); 7 if (0 == row_cnt) { 8 return false; 9 } 10 int col_cnt = matrix.at(0).size(); 11 if (target > matrix.at(row_cnt - 1).at(col_cnt - 1)) { 12 return false; 13 } 14 15 vector<int> row_max; 16 for (vector<vector<int> >::iterator iter = matrix.begin(); 17 iter != matrix.end(); ++iter) { 18 row_max.push_back(iter->at(col_cnt - 1)); 19 } 20 int target_row = std::lower_bound(row_max.begin(), row_max.end(), target) - row_max.begin(); 21 return std::binary_search(matrix.at(target_row).begin(), 22 matrix.at(target_row).end(), target); 23 24 } 25 };