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
.
从右上角开始,如果当前的数大于target,列号减一(左移一列),如果当前的数小于target,行号加一(下移一行)。
从左下角开始找也是一样的。
1 /** 2 * @param {number[][]} matrix 3 * @param {number} target 4 * @return {boolean} 5 */ 6 var searchMatrix = function(matrix, target) { 7 return findTarget(0, matrix[0].length - 1); 8 9 function findTarget(i, j){ 10 if(matrix[i][j] === target){ 11 return true; 12 } 13 if(matrix[i][j] > target){ 14 if(!matrix[i][j - 1]){ 15 return false; 16 }else{ 17 return findTarget(i, j - 1); 18 } 19 } 20 if(matrix[i][j] < target){ 21 if(!matrix[i + 1]){ 22 return false; 23 }else{ 24 return findTarget(i + 1, j); 25 } 26 } 27 } 28 };