题目:
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) { if (matrix.size()==0) return false; const int ROW = matrix.size(); const int COL = matrix[0].size(); // search the target row int begin = 0; int end = ROW-1; while ( begin<=end ) { int mid = (begin+end)/2; int lower = matrix[mid][0]; int upper = matrix[mid][COL-1]; if ( target>=lower && target<=upper ) { return Solution::binarySearch(matrix[mid], target); } if ( target<lower ) { end = mid-1; continue; } if ( target>upper ) { begin = mid+1; continue; } } return false; } static bool binarySearch(vector<int>& row, int target) { int begin = 0; int end = row.size()-1; while ( begin<=end ) { int mid = (begin+end)/2; if ( row[mid]==target ) return true; if ( row[mid]>target ) { end = mid-1; } else { begin = mid+1; } } return false; } };
tips:
1. 首先二分查找可能所在的行
2. 确定某一行之后,再二分查找所在的列
完毕。
时间: 2024-11-07 21:47:20