Solution in Java


  • 0
    D

    Just wanted to share my solution for the problem. (:

    public boolean searchMatrix(int[][] matrix, int target) {
            //Check that the matrix isn't empty
            if (matrix.length == 0 || matrix[0].length == 0) return false;
            
            //Check that the target is inside the matrix
            if (target < matrix[0][0] || target > matrix[matrix.length - 1][matrix[matrix.length - 1].length - 1]) return false;
            
            //Loop through the rows
            for (int i = 0; i < matrix.length; i++) {
                //Before looping through the columns check that the target could be inside
                if (target >= matrix[i][0] && target <= matrix[i][matrix[i].length - 1]) {
                    //Loop through columns
                    for (int j = 0; j < matrix[i].length; j++) {
                        //If target is smaller than the current number we wont find the target in this row since it's sorted                                ascending, so break the iteration and go to the next row
                        if (target < matrix[i][j]) break;
                        //If it's a match return true
                        if (target == matrix[i][j]) return true;
                    }
                }
            }
            return false;
        }
    

Log in to reply
 

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