How do I search for a number in a 2d array sorted left to right and top to bottom?

后端 未结 20 720
暖寄归人
暖寄归人 2020-11-22 13:03

I was recently given this interview question and I\'m curious what a good solution to it would be.

Say I\'m given a 2d array where all the numbers i

20条回答
  •  清酒与你
    2020-11-22 13:22

    public boolean searchSortedMatrix(int arr[][] , int key , int minX , int maxX , int minY , int maxY){
    
        // base case for recursion
        if(minX > maxX || minY > maxY)
            return false ;
        // early fails
        // array not properly intialized
        if(arr==null || arr.length==0)
            return false ;
        // arr[0][0]> key return false
        if(arr[minX][minY]>key)
            return false ;
        // arr[maxX][maxY] key ? search left quad matrix ;
        else {
             return(searchSortedMatrix(arr , key , minX,midX-1,minY,midY-1));
        }
        return false ;
    
    }
    

提交回复
热议问题