标签:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
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
.
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 };
[LeetCode][JavaScript]Search a 2D Matrix II
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4676195.html