question: 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-Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true my solution:
var searchMatrix = function(matrix, target) {
//first,decide target in which row
//insert search in this row
let row=matrix.length,col=matrix[0].length
let arr=null
for(let i=0;i<row;i++){
if(target<=matrix[i][col-1]&&target>=matrix[i][0]){
arr=matrix[i]
}
}
if(arr==null) return false
return insection(arr,target)
function insection(nums,tar){
let len=Math.ceil(nums.length/2)
if(nums[len]==tar){
return true
}
else if(nums[len]>tar){
insection(nums.slice(0,len),tar)
}else if(nums[len]<tar){
insection(nums.slice(len+1),tar)
}else{
return false
}
}
};
Don't know why my solution return "undefined"?