0

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"?

  • You need to use `return intersection(...)` inside the function. – Barmar Feb 24 '21 at 23:21
  • the branches of `insection` that just call `insection(...)` don't return anything. I haven't studied the logic but you probably want to put a `return` before that call, so that the recursive results actually pull through. – Robin Zigmond Feb 24 '21 at 23:22
  • @RobinZigmond if(nums[len]==tar){ return true } should return true? – Alex Zhang Feb 24 '21 at 23:53

0 Answers0