LeetCode之Flipping an Image(Kotlin)

weixin_34370347發表於2019-01-01

問題: Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].


方法: 參考程式碼實現。

具體實現:

class FlippingAnImage {
    fun flipAndInvertImage(A: Array<IntArray>): Array<IntArray> {
        for (i in A.indices) {
            for (j in 0..A.lastIndex / 2) {
                val temp = A[i][j]
                A[i][j] = invert(A[i][A.lastIndex - j])
                A[i][A.lastIndex - j] = invert(temp)
            }
        }
        return A
    }

    private fun invert(num: Int): Int {
        if (num == 0) {
            return 1
        } else {
            return 0
        }
    }
}

fun main(args: Array<String>) {
    val array = arrayOf(intArrayOf(1, 1, 0), intArrayOf(1, 0, 1), intArrayOf(0, 0, 0))
    val flippingAnImage = FlippingAnImage()
    flippingAnImage.flipAndInvertImage(array)
    CommonUtils.print2DIntArray(array)
}
複製程式碼

有問題隨時溝通

具體程式碼實現可以參考Github

相關文章