Beats only 70%, but clean solution. Need suggestions?


  • 0
    V
    public boolean searchMatrix(int[][] matrix, int target) {
        
        if (matrix.length == 0 || matrix[0].length == 0) return false;
        
        for (int i = 0; i < matrix.length; i++) {
            if (target == matrix[i][matrix[i].length - 1]) {
                return true;
            } else if (target < matrix[i][matrix[i].length - 1]) {
                return searchRow (matrix[i], target);
            }
        }
        
        return false;
    }
    
    public boolean searchRow (int[] matrix, int target) {
        
        int start = 0;
        int end = matrix.length - 1;
        int mid = 0;
        while (start <= end) {
            mid = start + (end - start) / 2;
            //System.out.println(mid + " Element: " + matrix[mid]);
            if (matrix[mid] == target) return true;
            else if (target < matrix[mid]) end = mid - 1;
            else start = mid + 1;
        }
        
        return false;
    }
    

    I'm only able to beat 70% of the solutions. How do I make this better?

    My approach:

    I look at the last element of each row and compare it to target, if target < the last element of that row, I do a binary search on that row.

    Please advice.


Log in to reply
 

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