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] ]
思想:两次二分查找
- bool searchMatrix(vector<vector<int> > &matrix, int target) {
- int row=matrix.size();
- if(row==0) return false;
- int col=matrix[0].size();
- if(col==0) return false;
- int low=0;
- int end=row-1;
- int line=-1;
- bool flag=false;
- int mid=0;
- while(low<=end) {
- mid=low+(end-low)/2;
- if(target==matrix[mid][0]) {
- line=mid;
- flag=true;
- break;
- }
- if(target<matrix[mid][0]) {
- end=mid-1;
- } else {
- low=mid+1;
- }
- }
- if(flag) {
- return true;
- } else {
- line=end;
- }
- if(line<0) return false;
- //if(line==row) line=row-1;
- low=0;
- end=col-1;
- while(low<=end) {
- mid=low+(end-low)/2;
- if(target==matrix[line][mid]) {
- //line=mid;
- return true;
- }
- if(target<matrix[line][mid]) {
- end=mid-1;
- } else {
- low=mid+1;
- }
- }
- return false;
- }

浙公网安备 33010602011771号