24
07/2015
[LeetCode] Search a 2D Matrix II
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.
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
.
解题思路:
咋一看,还不知如何下手,因为这样不能像此前Search a 2D Matrix那样,将二维坐标转化成一维坐标。其实可以从二维的角度来将矩阵划分。
矩阵中心为9,其中左上角的所有元素均小于等于9,右下角的元素均大于9。因此,我们可以每次对比矩阵中心元素,然后排出左上角或右下角区域即可。下面是代码:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if(m<=0){ return false; } int n = matrix[0].size(); if(n<=0){ return false; } return searchMatrixHelper(matrix, 0, m-1, 0, n-1, target); } bool searchMatrixHelper(vector<vector<int>>& matrix, int startM, int endM, int startN, int endN, int target){ if(startM > endM || startN > endN){ return false; } int middleM = (startM + endM) / 2; int middleN = (startN + endN) / 2; if(matrix[middleM][middleN]==target){ return true; }else if(matrix[middleM][middleN]<target){ return searchMatrixHelper(matrix, startM, endM, middleN + 1, endN, target) || searchMatrixHelper(matrix, middleM + 1, endM, startN, middleN, target); }else{ return searchMatrixHelper(matrix, startM, middleM - 1, startN, endN, target) || searchMatrixHelper(matrix, middleM, endM, startN, middleN - 1, target); } } };
转载请注明:康瑞部落 » [LeetCode] Search a 2D Matrix II
0 条评论