[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.

分析

题目的意思是:给定一个mxn的二进制矩阵,思路是把每一行变成全0和全1,并记录改变的位置,放在字典里面进行统计。

代码

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())

代码二

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})

参考文献

Python use dictionary of row flip Ops

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值