[leetcode] 1072. Flip Columns For Maximum Number of Equal Rows

Description

You are given an m x n binary matrix matrix.

You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).

Return the maximum number of rows that have all values equal after some number of flips.

Example 1:

Input: matrix = [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.

Example 2:

Input: matrix = [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.

Example 3:

Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 300
  • matrix[i][j] is either 0 or 1.

analysis

The meaning of the question is: given a binary matrix of mxn, the idea is to change each row into all 0s and all 1s, record the changed position, and put it in the dictionary for statistics.

Code

class Solution:
    def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
        cnt=Counter()
        for row in matrix:
            cnt[tuple(i for i,x in enumerate(row) if x!=0)]+=1
            cnt[tuple(i for i,x in enumerate(row) if x==0)]+=1
        return max(cnt.values())

Code two

from collections import Counter

class Solution:
    def maxEqualRowsAfterFlips(self, matrix) -> int:
        cnt=Counter()
        for row in matrix:
            cnt[tuple(i for i,x in enumerate(row) if x!=0)]+=1
            cnt[tuple(i for i,x in enumerate(row) if x==0)]+=1
        print(cnt)
        return max(cnt.values())

if __name__=="__main__":
    solution=Solution()
    # matrix = [[0,1],[1,1]]
    matrix = [[0,0,0],[0,0,1],[1,1,0]]
    res=solution.maxEqualRowsAfterFlips(matrix)
    print(res)
    # Counter({(2,): 2, (0, 1): 2, (): 1, (0, 1, 2): 1})

references

Python use dictionary of row flip Ops

Guess you like

Origin blog.csdn.net/w5688414/article/details/114224747