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, [18, 21, 23, 26, 30]
Given target = 5
, return true
.
Given target = 20
, return false
.
https://leetcode.com/problems/search-a-2d-matrix-ii/ From the upper-right corner, if the current number is greater than target, the column number is reduced by one (one column to the left), and if the current number is less than target, the line number is added one (the next row). It's the same from the bottom left corner.
1 /**2 * @param {number[][]} matrix3 * @param {number} target4 * @return {Boolean}5 */6 varSearchmatrix =function(matrix, target) {7 returnFindtarget (0, Matrix[0].length-1);8 9 functionFindtarget (i, j) {Ten if(Matrix[i][j] = = =target) { One return true; A } - if(Matrix[i][j] >target) { - if(!matrix[i][j-1]){ the return false; -}Else{ - returnFindtarget (i, j-1); - } + } - if(Matrix[i][j] <target) { + if(!matrix[i + 1]){ A return false; at}Else{ - returnFindtarget (i + 1), j); - } - } - } -};
[Leetcode] [JavaScript] Search a 2D Matrix II