74. Search a 2D Matrix(js)
74. Search a 2D Matrix
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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
Example 2:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
题意:给定一个s形排好序的二维数组,问我们数组中是否存在目标值target
代码如下:
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */ //比较数组行的第一项,若大于target,则遍历下一行,小于target,二分法查找本行 var searchMatrix = function(matrix, target) { if(matrix.length===0 || matrix===null || matrix[0].length===0) return false; var low=0; var high=matrix.length-1; while(low<=high){ var mid=parseInt((low+high)/2); if(matrix[mid][0]===target) return true; else if(matrix[mid][0]>target) high=mid-1; else low=mid+1; } //找到可能存在target行 var row=high; if(row<0) return false; low=0; high=matrix[0].length-1; while(low<=high){ var mid=parseInt((low+high)/2); if(matrix[row][mid]===target) return true; else if(matrix[row][mid]>target) high=mid-1; else low=mid+1; } return false; }