zoukankan      html  css  js  c++  java
  • 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.

    解题思路:

    对于一个矩阵有两种变换,行和列上面的取反。

    对于行变换,若首位数字不为1时,将进行行变化,此时整体数值变大。

    对于列变换,从第二列开始,统计每列的1和0的个数,若0的个数多余1的个数时,进行列变换,此时整体数值变大。

    代码:

     1 class Solution {
     2 public:
     3     int matrixScore(vector<vector<int>>& A) {
     4         for (auto & vec : A) {
     5             if (!vec[0])
     6                 togging(vec);
     7         }
     8         for (int i = 1; i < A[0].size() ; ++i){
     9             int zero = 0;
    10             int one = 0;
    11             for (int j = 0; j < A.size(); ++j){
    12                 if (A[j][i])
    13                     one++;
    14                 else
    15                     zero++;
    16             }
    17             if (zero>one){
    18                 for (int j = 0; j < A.size(); j++){
    19                     A[j][i] = !A[j][i];
    20                 }
    21             }
    22         }
    23         int num = 0;
    24         for (auto vec :A) {
    25             for (int i = 0; i < vec.size(); i++){
    26                 num += vec[i] *pow(2, (vec.size()-1-i));
    27             }
    28         }
    29         return num;
    30     }
    31     void togging(vector<int>& vec){
    32         for(int i = 0; i <vec.size(); i++){
    33             vec[i] = !vec[i];
    34         }
    35     }
    36 };
  • 相关阅读:
    RMAN备份脚本执行遇到RMAN-03002,06091问题处理
    物化视图日志过大,手工清理
    大表添加一个字段需求
    oracle_job进程相关学习测试
    11.2.0.4单实例静默安装
    RMAN执行crosscheck archive报错ORA-19633问题处理
    df执行hang住
    应用人员反馈报错,ORA-03137: TTC protocol internal error : [12333]
    普通表分区改造_rename方式
    SQL查询oracle数据库最近备份情况
  • 原文地址:https://www.cnblogs.com/gsz-/p/9384851.html
Copyright © 2011-2022 走看看