Daily question – Flip by column to get the maximum number of equal rows


Given a matrix consisting of several zeros and ones, select any number of columns from the matrix and flip each cell on it. After flipping, the value of the cell changes from 0 to 1, or from 1 to 0.

Returns the maximum number of rows on which all values are equal after some flipping.

Source: leetcode
Link: https://leetcode-cn.com/problems/flip-columns-for-maximum-number-of-equal-rows

My thinking:

This problem is not very good, read other people’s analysis to suddenly realize!

If two rows can be the same by flipping the same column, then the value XOR of the same position of two rows is equal to all 1.
According to the characteristics of XOR operation:
a ^ b = c
a ^ c = b

We know that C is all 1. Is there any good way to unify all lines with a unified rule?
We know that each position of a row with the same characteristics is different. Can we stipulate that the first one with “0” is a and the first one with “1” is B?
The specific rule is,
1 if the first digit is 0, then the whole line is converted to string type without XOR operation, and saved as key, with value + 1.
2 if the first bit is 1, then XOR the value in each position of the whole line with 1, then convert it to string type, save it as key, and value + 1.

Finally, traverse the map to get the largest value.

class Solution {
  int maxEqualRowsAfterFlips(vector>& matrix) {
            unordered_map m;
            int res = 0;
//For each line, convert the line to a string
            for (auto& r : matrix) {
                string s;
Int d = 0 ^ R [0]; / / if the first digit is 1, XOR with 1 becomes 1, which means that this line needs to be negated;
                for (auto x : r) {
                    s += (d ^ x)+48;
++M [S]; / / count the number of each row
                res = max(res, m[s]);
            return res;


Recommended Today

How does git store data

How does git store data Git is one of the tools that we use most every day. It is a new version control tool created by Linus Torvalds, the earliest author of Linux kernel. It is as simple and easy to use as Linux. This article will briefly talk about how git works requirement I […]