Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

1072. Flip Columns For Maximum Number of Equal Rows #68

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

1072. Flip Columns For Maximum Number of Equal Rows

给定由若干 0 和 1 组成的矩阵 matrix,从中选出任意数量的列并翻转其上的 每个 单元格。翻转后,单元格的值从 0 变成 1,或者从 1 变为 0 。

返回经过一些翻转后,行上所有值都相等的最大行数。

Example 1

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

Example 2

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

Example 3

Input: [[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

Tcdian commented 4 years ago

Solution (Hash Table)

func maxEqualRowsAfterFlips(matrix [][]int) int {
    record := make(map[string]int);
    maxResult := 0;
    for _, row := range matrix {
        origin := "";
        flipped := "";
        for _, number := range row {
            if number == 0 {
                origin += "0";
                flipped += "1";
            } else {
                origin += "1";
                flipped += "0";
            }
        }
        record[origin] += 1;
        record[flipped] += 1;
        maxResult = max(maxResult, max(record[origin], record[flipped]));
    }
    return maxResult;
}

func max(a int, b int) int {
    if a > b {
        return a;
    }
    return b;
}