Easy solution using binary search


  • 1
    W
    here I take the whole 2d matrix as a 1d array, from 0 to m*n - 1 thus you can use the binary search
    to solve this problem 
    bool binaryhelp(int **a, int m, int n, int target){
    int left = 0;
    int right = m*n - 1;
    while(left <= right){
        int mid = (left + right) / 2;
        int row = mid / n;
        int col = mid % n;
        if(a[row][col] == target){
            return true;
        }
        else if(a[row][col] > target){
            right = mid -1 ;
        }
        else{
            left = mid + 1;
        }
    }
    return false;
    

    }

     bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
    int m = matrixRowSize;
    int n = matrixColSize;
    /*(for(int i = 0; i < m; i++){
       if(binarysearch(matrix[i], target,n)){
           return true;
       }
    }
    return false;*/
    return binaryhelp(matrix, m, n, target);
      }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.