Search a 2D Matrix II
Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted in ascending from left to right.
- Integers in each column is sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, one, a], [2, 5, 8, 3, 6, 9, +, + ], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]]
given target = 5
, Return true
.
Given Target = 20
, return false
.
Problem Solving Ideas:
At first glance, I do not know how to start, because this does not like the previous search a 2D matrix, the two-dimensional coordinates into one-dimensional coordinates. In fact, we can divide the matrix from two-dimensional angle.
The center of the matrix is 9, where all elements in the upper-left corner are less than or equal to 9, and the lower-right corner of the element is greater than 9. Therefore, we can compare the center element of the matrix each time and then drain the upper left or lower right corner. Here's the code:
Class Solution {Public:bool Searchmatrix (vector<vector<int>>& matrix, int target) {int m = Mat Rix.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, end N, 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); } }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Search a 2D Matrix II