题目链接
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:
Given target = 3, return true
解题思路
TODO (稍后补充)
解答代码
- 第一种方法(会超时): 二分查找
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty()) return false;
int rowCnt = matrix.size();
int colCnt = matrix[0].size();
int numCnt = rowCnt * colCnt;
int lineNo = rowCnt - 1;
int colNo = colCnt - 1;
while(lineNo >= 0 && colNo >= 0) {
if (matrix[lineNo][colNo] == target) return true;
if (matrix[lineNo][colNo] > target) {
int curNo = (lineNo+1)*(colNo+1);
int nextNo = curNo / 2;
lineNo = nextNo / (colCnt+1);
colNo = nextNo % (colCnt+1);
}
}
return false;
}
};