Search a 2D Matrix(leetcode)
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.size() == 0 || matrix[0].size() == 0) return false;
int left, right, middle;
int row = matrix.size();
int col = matrix[0].size();
left = 0;
right = row*col-1;
middle = (left + right) / 2;
int x, y;
if (matrix[0][0] == target || matrix[row-1][col-1] == target) return true;
if (matrix[0][0] > target || matrix[row-1][col-1] < target) return false;
while (true) {
x = middle / col;
y = middle % col;
if (matrix[x][y] == target) return true;
if (matrix[x][y] < target) {
left = middle;
} else {
right = middle;
}
if (right - left <= 1) return false;
middle = (left + right) / 2;
}
return true;
}
};