問題: 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].git
方法: 參考代碼實現。github
具體實現:bash
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)
}
複製代碼
有問題隨時溝通ui