关于
lintcode系列,第28题,题目网址:https://www.lintcode.com/problem/search-a-2d-matrix/description
描述
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.
样例:
样例 1:
输入: [[5]],2
输出: false
样例解释:
没有包含,返回false。
样例 2:
输入:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
],3
输出: true
样例解释:
包含则返回true。
思路
二分法的使用个,注意矩阵下标的转换。
C++实现
class Solution {
public:
/**
* @param matrix: matrix, a list of lists of integers
* @param target: An integer
* @return: a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
// write your code here
int m=matrix.size();
if(m == 0) {
return false;
}
int n=matrix[0].size();
int end=m*n,head=0;
while(head!=end) {
if(target == matrix[((head+end)/2)/n][((head+end)/2)%n]) {
return true;
}
else if(target < matrix[((head+end)/2)/n][((head+end)/2)%n]) {
end = (head+end)/2;
}
else {
head = (head+end)/2 + 1;
}
}
if(matrix[(head/2)/n][(head/2)%n] == target) return true;
else return false;
}
};