1. 程式人生 > 實用技巧 >leetcode-1072 Flip Columns For Maximum Number of Equal Rows

leetcode-1072 Flip Columns For Maximum Number of Equal Rows

Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column.  Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.

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

輸入輸出例項:

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

  本題可以使用dict,統計最多的相同的行出現的次數(row 和 reverse(row)視為同一行)

class Solution:
    def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
        def reverse_row(arr):
            res = [0] * len(arr)
            for item, values in enumerate(row):
                res[item] = 1 - values
            
return res dic = {} for row in matrix: if tuple(row) in dic: dic[tuple(row)] += 1 elif tuple(reverse_row(row)) in dic: dic[tuple(reverse_row(row))] += 1 else: dic[tuple(row)] = 1 dic = sorted(dic.items(), key = lambda
x:x[1], reverse=True) return dic[0][1]