LeetCode 240. Search a 2D Matrix II
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
解析:从二维数组中查找元素,这个题目是在题目LeetCode 74. Search a 2D Matrix基础上进行的升级。前一个题目是从左到右、从上到下都是有序的,并且前一行的最后一个元素小于后一行的第一个元素,这样整体就构成了一个一维有序数组,直接采用二分查找即可。现在这个题目只是说从前往后、从上到下是有序的。这样没法整体有二分查找了。此题目可以采用部分的二分查找和分治法。
方法1:
二分查找
可以考虑先大致确定行的范围,然后在这个范围内对所有行进行朱行二分查找。即:首先对第一列元素应用二分查找,确定行的范围。具体代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty())
return false;
if(target < matrix[0][0] || target > matrix.back().back())
return false;
// 确定行的范围
int low = 0;
int high = matrix.size()-1;
while(low <= high)
{
int mid = (low+high)/2;
if(matrix[mid][0] > target )
high = mid -1;
else if(matrix[mid][0] < target)
low = mid + 1;
else
return true;
}
for(int index = 0; index <= high; index ++)//对每一行进行二分查找
{
int l = 0, r = matrix[0].size()-1;
while(l <= r)
{
int mid = (l+r) /2;
if(matrix[index][mid] < target)
l = mid + 1;
else if(matrix[index][mid] > target)
r = mid -1;
else
return true;
}
}
return false;
}
};
运行结果:

方法2:
分治法
观察题目给定的二维数组会发现,左下角和右上角是两个特殊的位置,在左下角往上的元素都比当前元素小,往右的元素都比当前元素大,所以考虑采用分治法进行处理。
具体代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty())
return false;
if(target < matrix[0][0] || target > matrix.back().back())
return false;
int x = matrix.size() -1;
int y =0;
while(true)
{
if(target < matrix[x][y])
x--;
else if(target > matrix[x][y])
y++;
else
return true;
if(x < 0 || y >= matrix[0].size())
break;
}
return false;
}
};