My java solution 0ms


  • 0
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return list;
        int i = 0;
        int j = 0;
        int row = (matrix.length + 1) / 2;
        int col = (matrix[0].length + 1) / 2;
        while(i < row && j < col) {
          for(int k = j; k < matrix[0].length - j; k++) list.add(matrix[i][k]);
          for(int k = i + 1; k < matrix.length - i - 1; k++) list.add(matrix[k][matrix[0].length - j - 1]);
          if(matrix.length - i - 1 > i) for(int k = matrix[0].length - j - 1; k >= j; k--) list.add(matrix[matrix.length - i - 1][k]);
          if(matrix[0].length - j - 1 > j) for(int k = matrix.length - i - 2; k > i; k--) list.add(matrix[k][j]);
          i++;
          j++;
        }
        return list; 
    }

Log in to reply
 

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