50. 矩阵置零

RT

打卡个Scala泛型(数字)版

  // Time: O(m*n), Space: O(1)
  def setZeroInMatrixO1[T](matrix: Array[Array[T]])(implicit num: Numeric[T]): Unit = {
    val rowLen = matrix.length
    val colLen = matrix(0).length
    val row0 = matrix(0).contains(num.zero)
    val col0 = matrix.exists(arr => arr(0) == num.zero)

    for (i <- 1 until rowLen) {
      for (j <- 1 until colLen if matrix(i)(j) == num.zero) {
        matrix(i)(0) = num.zero
        matrix(0)(j) = num.zero
      }
    }
    for (i <- 1 until rowLen) {
      for (j <- 1 until colLen if matrix(i)(0) == num.zero || matrix(0)(j) == num.zero)
        matrix(i)(j) = num.zero
    }

    if (row0) (0 until colLen).foreach(j => matrix(0)(j) = num.zero)
    if (col0) (0 until rowLen).foreach(r => matrix(r)(0) = num.zero)
  }

// scalatest

  test("testSetZeroInMatrixO1-int") {
    val matrix = Array(Array(1, 2, 3), Array(4, 0, 6), Array(0, 8, 9))
    setZeroInMatrixO1(matrix)
    matrix should be(Array(Array(0, 0, 3), Array(0, 0, 0), Array(0, 0, 0)))
  }
  test("testSetZeroInMatrixO1-double") {
    val matrix: Array[Array[Double]] = Array(Array(1.1, 2.2, 3.3), Array(4.0, 0, 6.8), Array(0.0, 8.1, 9.9))
    val expected: Array[Array[Double]] = Array(Array(0, 0, 3.3), Array(0, 0, 0), Array(0, 0, 0))
    setZeroInMatrixO1(matrix)
    matrix should be(expected)
  }