返回介绍

solution / 1000-1099 / 1072.Flip Columns For Maximum Number of Equal Rows / README_EN

发布于 2024-06-17 01:03:31 字数 3895 浏览 0 评论 0 收藏 0

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.

Solutions

Solution 1

class Solution:
  def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
    cnt = Counter()
    for row in matrix:
      t = tuple(row) if row[0] == 0 else tuple(x ^ 1 for x in row)
      cnt[t] += 1
    return max(cnt.values())
class Solution {
  public int maxEqualRowsAfterFlips(int[][] matrix) {
    Map<String, Integer> cnt = new HashMap<>();
    int ans = 0, n = matrix[0].length;
    for (var row : matrix) {
      char[] cs = new char[n];
      for (int i = 0; i < n; ++i) {
        cs[i] = (char) (row[0] ^ row[i]);
      }
      ans = Math.max(ans, cnt.merge(String.valueOf(cs), 1, Integer::sum));
    }
    return ans;
  }
}
class Solution {
public:
  int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
    unordered_map<string, int> cnt;
    int ans = 0;
    for (auto& row : matrix) {
      string s;
      for (int x : row) {
        s.push_back('0' + (row[0] == 0 ? x : x ^ 1));
      }
      ans = max(ans, ++cnt[s]);
    }
    return ans;
  }
};
func maxEqualRowsAfterFlips(matrix [][]int) (ans int) {
  cnt := map[string]int{}
  for _, row := range matrix {
    s := []byte{}
    for _, x := range row {
      if row[0] == 1 {
        x ^= 1
      }
      s = append(s, byte(x)+'0')
    }
    t := string(s)
    cnt[t]++
    ans = max(ans, cnt[t])
  }
  return
}
function maxEqualRowsAfterFlips(matrix: number[][]): number {
  const cnt = new Map<string, number>();
  let ans = 0;
  for (const row of matrix) {
    if (row[0] === 1) {
      for (let i = 0; i < row.length; i++) {
        row[i] ^= 1;
      }
    }
    const s = row.join('');
    cnt.set(s, (cnt.get(s) || 0) + 1);
    ans = Math.max(ans, cnt.get(s)!);
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文