一.问题描述
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) {
int row_num = matrix.size();
if(row_num==0) return 0;
int line_num = matrix[0].size();
int total_num = row_num*line_num;
int st=0;int end=total_num-1;int mid;
while(st<end){
mid = (st+end)/2;
int curr_val = gen_val(matrix,mid);
if(curr_val==target) return 1;
if(curr_val<target) st=mid+1;
if(curr_val>target) end=mid-1;
}
if(st==end){
int curr_val = gen_val(matrix,st);
if(curr_val==target) return 1;
else return 0;
}
return 0;
}
int gen_val(vector<vector<int>>& matrix, int idx){
int row_num = matrix.size();
int line_num = matrix[0].size();
int i,j;
i=idx/line_num;
j=idx-i*line_num;
return matrix[i][j];
}
};