From : https://leetcode.com/problems/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.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size() || !matrix[0].size()) return false;
int startRow=0, start=0, endRow=matrix.size()-1, end=matrix[0].size()-1, midRow = 0;
while(startRow <= endRow) {
midRow = (startRow+endRow)>>1;
if(matrix[midRow][start] <= target && matrix[midRow][end] >= target) {
break;
}
else if(matrix[midRow][end] < target) {
startRow = midRow+1;
} else {
endRow = midRow-1;
}
}
if(matrix[midRow][start] > target || matrix[midRow][end] < target) return false;
while(start <= end) {
int mid = (start+end)>>1;
if(matrix[midRow][mid] == target) return true;
else if(matrix[midRow][mid] > target) {
end = mid-1;
} else {
start = mid+1;
}
}
return false;
}
};
本文介绍了一种高效的算法,用于在一个m x n的矩阵中查找特定值。该矩阵每一行的整数从左到右递增排序,并且每行的第一个整数大于前一行的最后一个整数。文章提供了一个具体的示例矩阵及目标值,并展示了如何使用C++实现搜索过程。
287

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



