題目
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.
For 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.
解題之法
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, y = 0;
while (true) {
if (matrix[x][y] > target) --x;
else if (matrix[x][y] < target) ++y;
else return true;
if (x < 0 || y >= matrix[0].size()) break;
}
return false;
}
};
分析
這道題讓我們在一個二維數(shù)組中快速的搜索的一個數(shù)字赊豌,這個二維數(shù)組各行各列都是按遞增順序排列的际看,是之前那道Search a 2D Matrix 搜索一個二維矩陣的延伸济炎,那道題的不同在于每行的第一個數(shù)字比上一行的最后一個數(shù)字大,是一個整體蛇形遞增的數(shù)組刹淌。所以那道題可以將二維數(shù)組展開成一個一位數(shù)組用一次二查搜索端壳。而這道題沒法那么做账忘,這道題有它自己的特點卫旱。如果我們觀察題目中給的那個例子,我們可以發(fā)現(xiàn)有兩個位置的數(shù)字很有特點骨饿,左下角和右上角的數(shù)亏栈。左下角的18台腥,往上所有的數(shù)變小,往右所有數(shù)增加绒北,那么我們就可以和目標數(shù)相比較黎侈,如果目標數(shù)大,就往右搜闷游,如果目標數(shù)小峻汉,就往左搜。這樣就可以判斷目標數(shù)是否存在脐往。當然我們也可以把起始數(shù)放在右上角休吠,往左和下搜,停止條件設置正確就行业簿。