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.
把二维矩阵变成一维来写binary search即可。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
int col = matrix[0].size();
int left = 0;
int right = row*col-1;
while(left<=right){//注意是小于等于
int mid = (left+right)/2;
int i = mid/col;
int j = mid%col;
if(matrix[i][j]==target){
return true;
}
if(matrix[i][j]<target){
left = mid+1 ;//important
}
else if(matrix[i][j]>target){
right = mid-1; //important
}
}
return false;
}
};
本文介绍了一种高效的搜索算法,用于在一特殊性质的二维矩阵中查找指定值。该矩阵的每一行从左到右递增排序,并且每行的第一个元素大于前一行的最后一个元素。文章提供了一个具体的例子和C++实现代码。
406

被折叠的 条评论
为什么被折叠?



