Java O(n^2) Layered


  • 0
    A
    public int[][] generateMatrix(final int n) {
            if (n <= 0) {
                return new int[][]{};
            }
    
            int[][] result = new int[n][n];
    
            for (int startRow = 0, endRow = n-1, startColumn = 0, endColumn = n-1, i=1;
                    startRow <= endRow && startColumn <= endColumn;
                    startRow++, endRow--, startColumn++, endColumn--) {
                for (int column = startColumn; column <= endColumn; column++) {
                    result[startRow][column] = i++;
                }
    
                for (int row = startRow+1; row <= endRow; row++) {
                    result[row][endColumn] = i++;
                }
    
                for (int column = endColumn-1; column >= startColumn; column--) {
                    result[endRow][column] = i++;
                }
    
                for (int row = endRow-1; row >= startRow+1; row--) {
                    result[row][startColumn] = i++;
                }
            }
    
            return result;
        }
    

Log in to reply
 

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