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.

Solution

Solved after help.

Assume the i-th row is all 0s after flipping x columns, then:

  1. If there are other rows that are also all 0s, then before flipping it must be the same as the current row.
  2. If there are other rows that are all 1s, then before flipping it must be totally different from the current row.

So the question transforms to: find the row that has most same rows and most totally different rows.

An intuitive way is to store all the values in one row in a map, and for every row, check if the value or the opposite value has appeared before. If did appear, then add the value. Otherwise create a new value 1.

Time complexity: o ( m ∗ n ) o(m*n) o(mn), o ( n ) o(n) o(n) for creating the row key, o ( m ) o(m) o(m) for iterating all the rows.
Space complexity: o ( m ∗ n ) o(m*n) o(mn)

Code

class Solution:
    def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
        row_cnt = {}
        for each_row in matrix:
            row_key = ''.join(map(str, each_row))
            oppo_row_key = ''.join('1' if x == '0' else '0' for x in row_key)
            if row_key in row_cnt:
                row_cnt[row_key] += 1
            elif oppo_row_key in row_cnt:
                row_cnt[oppo_row_key] += 1
            else:
                row_cnt[row_key] = 1
        return max(row_cnt.values())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值