題目鏈接
tag:
- Medium状勤;
question:
??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.
思路:
??本題讓我們?cè)谝粋€(gè)二維數(shù)組中快速的搜索的一個(gè)數(shù)字埃跷,這個(gè)二維數(shù)組各行各列都是按遞增順序排列的锚扎,是之前那道74. Search a 2D Matrix 搜索一個(gè)二維矩陣的延伸熟掂,那道題的不同在于每行的第一個(gè)數(shù)字比上一行的最后一個(gè)數(shù)字大嗜侮,是一個(gè)整體蛇形遞增的數(shù)組稽犁。所以那道題可以將二維數(shù)組展開成一個(gè)一維數(shù)組用一次二查搜索沮翔。而這道題沒(méi)法那么做陨帆,這道題有它自己的特點(diǎn)。我們觀察題目中給的那個(gè)例子采蚀,我們可以發(fā)現(xiàn)有兩個(gè)位置的數(shù)字很有特點(diǎn)疲牵,左下角和右上角的數(shù)。左下角的18榆鼠,往上所有的數(shù)變小纲爸,往右所有數(shù)增加,那么我們就可以和目標(biāo)數(shù)相比較妆够,如果目標(biāo)數(shù)大识啦,就往右搜,如果目標(biāo)數(shù)小神妹,就往上搜颓哮。這樣就可以判斷目標(biāo)數(shù)是否存在。當(dāng)然我們也可以把起始數(shù)放在右上角鸵荠,往左和下搜冕茅,停止條件設(shè)置正確就行。代碼如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty())
return false;
int m = matrix.size() - 1, n = matrix[0].size() - 1;
int row = 0, col = n;
while (row <= m && col >= 0) {
if (matrix[row][col] == target) return true;
else if (matrix[row][col] < target) ++row;
else --col;
}
return false;
}
};