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; } };