Clean easy solution in Java


  • 7
    X
    public boolean searchMatrix(int[][] matrix, int target) {
    	int line=0;
    	int len=matrix.length;
    	int col=matrix[0].length;
    	while (line<len && col>0){
    		int num= matrix[line][col-1];
    		if (num>target) col--;
    		if (num<target) line++;
    		if (num==target) return true;}
    	
        return false;
    }
    

    The main idea of this solution is to compare the target with the number in the top-right corner and decrease the row number or the col number one by one. It's simple and efficient.


Log in to reply
 

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