问题: 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

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐