• 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 };
  • 相关阅读:
    根据访问ip的地区跳转到指定地址
    js生成vCard,以及格式参数详细说明
    min_to_split_multiprocessing多进程,用于平时快速补充数据
    min_to_split.py按日存储到按个股存储
    readzip_minute_data 多进程处理数据
    打包成7zfile,to7zfile
    baostock_multiprocessing 多进程取数据
    终止阻塞线程(有共享锁的线程无效)
    readzip_add_maxL3多线程
    readzip_add_maxL2
  • 原文地址:https://www.cnblogs.com/gsz-/p/9384851.html
Copyright © 2020-2023  润新知