Clean, precise Java solution O(n2) time and O(1) space


  • 0
    R

    class Solution {
    public int[][] generateMatrix(int n) {

        int square = n*n;
        
        int[][] result = new int[n][n];
        
        int rowStart = 0, colStart = 0;.
        int rowEnd = n-1, colEnd = n-1;
        int count = 1;    
        
        while(count <= square) {
            for(int i = colStart; i <= colEnd; i++) {
                result[rowStart][i] = count;
                count++;
            }
            
            rowStart++;
            
            for(int i = rowStart; i <= rowEnd; i++) {
                result[i][colEnd] = count;
                count++;
            }
            
            colEnd--;
            
            for(int i = colEnd; i >= colStart; i--) {
                result[rowEnd][i] = count;
                count++;
            }
            
            rowEnd--;
            
            for(int i = rowEnd; i >= rowStart; i--) {
                result[i][colStart] = count;
                count++;
            }
            
            colStart++;
                
        }
        
        return result;
        
    }
    

    }


Log in to reply
 

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