题目:
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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
思路:
分两步,(1)先二分搜索的元素定位到行:当目标小于第一列某个元素时,向前面的行中去搜索;当目标大于第一列某个元素分两种情况 a、大于该元素所在行的最后一个元素时,往后面的行中去搜索,b、小于等于该元素所在行的最后一个元素,则可以定位到该元素所在的行。(2)在定位好的行中二分搜索
注意,在第一步查找所在行时,while(l<r)而不是whilel<=r;当target>nums[middle]时,还需要判断一下target和该行末的值,从而确定是否需要l=middle+1。
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */ var searchMatrix = function(matrix, target) { var m=matrix.length,n=matrix[0].length; var L=0,R=m-1,middle=0; while(L<R){ middle=L+Math.floor((R-L)/2); if(target<matrix[middle][0]){ R=middle-1; }else if(target>matrix[middle][0]){ if(target>matrix[middle][n-1]){ L=middle+1; }else{ L=middle; break; } }else{ return true; } } var row=L; var l=0,r=n-1,middle=0; while(l<=r){ middle=l+Math.floor((r-l)/2); if(matrix[row][middle]>target){ r=middle-1; }else if(matrix[row][middle]<target){ l=middle+1; }else{ return true; } } return false; };