【LeetCode】861. Score After Flipping Matrix 翻转矩阵后的得分(Medium)(JAVA)

【LeetCode】861. Score After Flipping Matrix 翻转矩阵后的得分(Medium)(JAVA)

题目地址: https://leetcode.com/problems/score-after-flipping-matrix/

题目描述:

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.

Example 1:

Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Note:

  • 1 <= A.length <= 20
  • 1 <= A[0].length <= 20
  • A[i][j] is 0 or 1.

题目大意

有一个二维矩阵 A 其中每个元素的值为 0 或 1 。

移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。

在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。

返回尽可能高的分数。

解题方法

  1. 为了让矩阵的得分尽可能高,第一列肯定是全部需要变成 1: 对每一行遍历,如果第一个不为 1,就把整行翻转
  2. 为了让每一列的得分最高,如何判断这里列要不要翻转呢?就看这一列 1 的个数是否超过一般,如果超过了一半就不需要翻转,如果没超过就需要翻转
  3. 在遍历的过程中把总合也计算出来
class Solution {
    public int matrixScore(int[][] A) {
        if (A.length == 0 || A[0].length == 0) return 0;
        int sum = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i][0] == 1) continue;
            for (int j = 0; j < A[0].length; j++) {
                A[i][j] ^= 1;
            }
        }
        sum += (1 << (A[0].length - 1)) * A.length;
        int half = (A.length + 1) / 2;
        for (int i = 1; i < A[0].length; i++) {
            int count = 0;
            for (int j = 0; j < A.length; j ++) {
                if (A[j][i] == 1) count++;
            }
            sum += (1 << (A[0].length - i - 1)) * Math.max(count, A.length - count);
            if (count >= half) continue;
            for (int j = 0; j < A.length; j ++) {
                A[j][i] ^= 1;
            }
        }
        return sum;
    }
}

执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36.3 MB,击败了68.22% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值