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
.
方法一,先纵向查找,再横向查找,时间复杂度为O(logm)+O(logn)
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int n = matrix.size(), m = matrix[0].size(); if(target < matrix[0][0] || target >matrix[n-1][m-1]) return false; int left = 0 , right = n-1, targetRow = 0; //纵向二分查找 while(left <= right){ int mid = (left+right)>>1; if(matrix[mid][0] > target ) right = mid-1; else if(matrix[mid][0] < target) left = mid+1; else break; } if(left>right) targetRow =right; else return true; //横向二分查找 left = 0;right = m-1; while(left <= right){ int mid = (left+right)>>1; if(matrix[targetRow][mid] > target) right = mid-1; else if(matrix[targetRow][mid] < target) left = mid+1; else break; } if(left <=right ) return true; else return false; } };
方法二,直接二分查找
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int n = matrix.size(), m = matrix[0].size(); if(target < matrix[0][0] || target >matrix[n-1][m-1]) return false; int left = 0 , right = n*m-1; while(left<=right){ int mid = (left+right)>>1; if(matrix[mid/m][mid%m] > target) right = mid-1; else if(matrix[mid/m][mid%m] < target) left = mid+1; else return true; } return false; } };