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.
Code:
<span style="font-size:14px;">class Solution {
public:
bool searchArray(vector<int> &array, int begin, int end, const int &target) {
if (begin > end) return false;
int mid = (begin+end)/2;
if (array[mid] == target) return true;
else if (array[mid] < target) return searchArray(array, mid+1, end, target);
else return searchArray(array, begin, mid-1, target);
}
bool helper(vector<vector<int> > &matrix, int begin, int end, const int &target, const int &cols) {
if (begin > end) return false;
int mid = (begin+end)/2;
if (matrix[mid][0] <= target && target <= matrix[mid][cols-1]) return searchArray(matrix[mid], 0, cols-1, target);
else if (target < matrix[mid][0]) return helper(matrix, begin, mid-1, target, cols);
else helper(matrix, mid+1, end, target, cols);
}
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int rows = matrix.size();
if (rows == 0) return false;
int cols = matrix[0].size();
return helper(matrix, 0, rows-1, target, cols);
}
};</span>

本文介绍了一种高效的搜索算法,用于在一特殊格式的二维矩阵中查找指定的目标值。该矩阵每一行从左到右元素递增排序,且每行首元素大于前一行末尾元素。通过递归二分查找实现快速定位。

112

被折叠的 条评论
为什么被折叠?



