My simple java 0ms solution


  • 1
    W

    public class Solution {

    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null) return false;
        
        int rowLen = matrix.length, colLen = matrix[0].length;
        
        if(target < matrix[0][0] || target > matrix[rowLen - 1][colLen - 1]) return false;
        
        int index = -1;
        for(int i=0; i<rowLen; i++){
            if(matrix[i][0] <= target && matrix[i][colLen - 1] >= target){index = i; break;}
            else continue;
        }
        
        if(index == -1) return false;
        
        for(int j=0; j<colLen; j++)
            if(target == matrix[index][j]) return true;
        
        return false;
    }
    

    }


  • 0
    N

    I think your solution works well for the input provided for this problem but the solution doesn't make use of the sorted rows and sorted columns at all. I suppose when the question is asked in the interview, the motive would be make use of the sorted input - so interviewer would probably want to know about binary search.


  • 0
    W

    yes, I know, thanks~


Log in to reply
 

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