LeetCode之Score After Flipping Matrix(Kotlin)

问题:
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.


方法:
使最终结果最大一共需要做两部操作:
1)遍历所有行的第一个元素,如果为0则反转该行,保证每个二进制数的最高位都为1
2)遍历所有列(不包含首列,因为首列为最高位),如果该列0的个数多于一半则反转该列
经过如上两部操作之后则矩阵的结果即为最大

具体实现:

import kotlin.math.abs

class ScoreAfterFlippingMatrix {
    fun matrixScore(A: Array<IntArray>): Int {
        for (i in A.indices) {
            if (A[i][0] == 0) {
                for (j in A[0].indices) {
                    A[i][j] = abs(A[i][j] - 1)
                }
            }
        }
        for (j in 1..A[0].lastIndex) {
            var zeroNum = 0
            for (i in A.indices) {
                if (A[i][j] == 0) {
                    zeroNum++
                }
            }
            if (zeroNum * 2 > A.size) {
                for (i in A.indices) {
                    A[i][j] = abs(A[i][j] - 1)
                }
            }
        }
        var sum = 0
        for (i in A.indices) {
            for (j in A[0].indices) {
                sum += A[i][j] shl (A[0].lastIndex - j)
            }
        }
        return sum
    }
}

fun main(args: Array<String>) {
    val array = arrayOf(intArrayOf(0, 0, 1, 1), intArrayOf(1,0 ,1, 0), intArrayOf(1, 1, 0, 0))
//    val array = arrayOf(intArrayOf(0, 1), intArrayOf(1,1))
    val scoreAfterFlippingMatrix = ScoreAfterFlippingMatrix()
    val result = scoreAfterFlippingMatrix.matrixScore(array)
    print("result: $result")
}

有问题随时沟通

具体代码实现可以参考Github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值