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
.
题意
判断一个矩阵中是否包含目标元素,矩阵有两个特性:从左到右排序;每一行第一个元素比上一行最后一个元素大。
题解
使用二分法,把矩阵看成是一维数据处理。 长度为col*raw 用的时候下标为 mid/row mid%row
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
const size_t high=matrix.size();
const size_t len=matrix[0].size();
int begin=0,end=high*len-1,mid=0;
while(begin<end)
{
mid=(begin+end)/2;
int val=matrix[mid/len][mid%len];
if(val==target) return true;
if(val>target) end=mid;
else begin=mid+1;
}
if(matrix[begin/len][begin%len]==target ) return true;
return false;
}
};