標籤:
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.
https://leetcode.com/problems/search-a-2d-matrix-ii/ 從右上方開始,如果當前的數大於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 };
[LeetCode][JavaScript]Search a 2D Matrix II