leetcode 5077. inverted by column to give the maximum number of lines and the like (Flip Columns For Maximum Number of Equal Rows)

Subject description:

To a matrix composed of 0 and 1 by a number of predetermined matrix, selected from any number of columns and turn each cell thereon. After inversion, the cell value from 0 to 1, or from 1 to 0.

After some maximum number of rows returned flip on line all values ​​are equal.

Example 1:

输入:[[0,1],[1,1]]
输出:1
解释:不进行翻转,有 1 行所有值都相等。

Example 2:

输入:[[0,1],[1,0]]
输出:2
解释:翻转第一列的值之后,这两行都由相等的值组成。

Example 3:

输入:[[0,0,0],[0,0,1],[1,1,0]]
输出:2
解释:翻转前两列的值之后,后两行由相等的值组成。

prompt:

  • 1 <= matrix.length <= 300
  • 1 <= matrix[i].length <= 300
  • All matrix[i].lengthare equal
  • matrix[i][j] 0 or 1

solution:

class Solution {
public:
    bool valid(vector<int>& lst1, vector<int>& lst2){
        int sz = lst1.size();
        int pre = lst1[0]^lst2[0];
        for(int i = 1; i < sz; i++){
            if((lst1[i]^lst2[i]) != pre){
                return false;
            }
        }
        return true;
    }
    
    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> tag(m, 0);
        for(int i = 1; i < m; i++){
            tag[i] = i;
            for(int j = 0; j < i; j++){
                if(valid(matrix[j], matrix[i])){
                    tag[i] = tag[j];
                    break;
                }
            }
        }
        vector<int> lst(300, 0);
        for(int val : tag){
            // cout<<val<<endl;
            lst[val]++;
        }
        int res = 0;
        for(int val : lst){
            res = max(res, val);
        }
        return res;
    }
};

Guess you like

Origin www.cnblogs.com/zhanzq/p/10974083.html