这道题本质还是二分查找,和普通的有所不同的是要进行两次。因为每列每行都是有序的,所以在定位行以后再定位列。
function searchMatrix( matrix , target ) { // write code here let up = 0,down = matrix.length-1 let row = 0 while(up<=down){//定位行 let mid = Math.floor((up+down)/2) if(matrix[mid][0]<=target){ if(mid==matrix.length-1||matrix[mid+1][0]>target){ row = mid break }else{ up = mid+1 row = up } }else{ down = mid-1 row = down } } if(row==-1) return false//如果没有找到直接返回false let left = 0,right = matrix[0].length-1 while(left<=right){//定位列 let mid = Math.floor((left+right)/2) if(matrix[row][mid]<=target){ if(matrix[row][mid]==target) return true//找到 else{ left = mid+1 } }else{ right = mid-1 } } return false }