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
.
基本思路:
1. 先用折半查找,定位到行。
2. 再用折半查找,定位到列。
這裡用到的是二段式,二分法查找, 即循環中,隻有2個分支,省掉 判等的分支。
在第一次二分退出循環後,需要判斷,待查找值,位于目前行前,或者是前一行。
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
if (matrix.empty() || matrix[0].empty())
return false;
int low = 0, high = matrix.size()-1;
while (low < high) {
const int mid = low + (high - low) / 2;
if (matrix[mid][0] < target)
low = mid + 1;
else
high = mid;
}
const int row = low && matrix[low][0] > target ? low - 1: low;
low = 0, high = matrix[row].size()-1;
while (low < high) {
const int mid = low + (high - low) / 2;
if (matrix[row][mid] < target)
low = mid + 1;
else
high = mid;
}
return matrix[row][low] == target;
}
};
此題可以把二維數組,當成一個一維有序數組進行折半查找。
但需要一個将一維坐标,轉換成二維坐标的過程。 将需要額外進/和%的運算。