關於
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;
}
};