• LC 861. 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. 1 <= A.length <= 20
    2. 1 <= A[0].length <= 20
    3. A[i][j] is 0 or 1.

    Runtime: 4 ms, faster than 58.17% of C++ online submissions for Score After Flipping Matrix.

    注意一下,首列如果某行从0换成1那么在之后计算这一行时要反向。

    class Solution {
    public:
      int matrixScore(vector<vector<int>>& A) {
        int r = A.size();
        int c = A[0].size();
        vector<int> rsign(r,0);
        int base = 1 << (A[0].size()-1), ret = 0;
        for(int j=0; j<c; j++){
          int cntzero = 0, cntone = 0;
          for(int i=0; i<r; i++){
            if(j == 0){
              if(A[i][j] != 0) rsign[i]++;
            }else{
              if((A[i][j] == 0 && rsign[i] == 0) || (A[i][j] == 1 && rsign[i] == 1)) cntzero++;
              else cntone++;
            }
          }
          if(j == 0){
            ret += base * r;
          } else if(cntzero > cntone) {
            ret += base * cntzero;
          }else ret += base * cntone;
          base >>= 1;
        }
        
        return ret;
      }
    };
  • 相关阅读:
    libuv 中文编程指南(一)序言
    一些鲜为人知却非常实用的数据结构
    libuv 中文编程指南(二)libuv 基础
    Zookeeper 的 Lua 绑定(二)
    高度怀疑
    不能没有你
    第一次看流星雨记
    调侃下蓝网队 我还是比较极端的 不要好 那就要坏吧
    摇滚校园
    守法公民
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10177241.html
Copyright © 2020-2023  润新知