Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:html
For example,數組
Consider the following matrix:ide
[ [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
.code
Given target = 20
, return false
.htm
忽然發現LeetCode很喜歡從LintCode上盜題,這是逼我去刷LintCode的節奏麼?! 這道題讓咱們在一個二維數組中快速的搜索的一個數字,這個二維數組各行各列都是按遞增順序排列的,是以前那道Search a 2D Matrix 搜索一個二維矩陣的延伸,那道題的不一樣在於每行的第一個數字比上一行的最後一個數字大,是一個總體蛇形遞增的數組。因此那道題能夠將二維數組展開成一個一位數組用一次二查搜索。而這道題無法那麼作,這道題有它本身的特色。若是咱們觀察題目中給的那個例子,咱們能夠發現有兩個位置的數字頗有特色,左下角和右上角的數。左下角的18,往上全部的數變小,往右全部數增長,那麼咱們就能夠和目標數相比較,若是目標數大,就往右搜,若是目標數小,就往上搜。這樣就能夠判斷目標數是否存在。固然咱們也能夠把起始數放在右上角,往左和下搜,中止條件設置正確就行。代碼以下:blog
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; } };