DEV Community

vc7
vc7

Posted on

LeetCode in Swift - 1072. Flip Columns For Maximum Number of Equal Rows

Problem

Data Structure

  • Hash map

Approach and the Routine

Base on the problem and the examples, a flip means, if there is a 0 will become 1 and if there is a 0 will become 1.

Normalize the rows

Because we only have to find the maximum number of all 0s and all 1s rows after a certain flipping of columns, which means we have to find the most appeared pattern.

01 -> 11 (Satisfied)
10 -> 00 (Satisfied)
Enter fullscreen mode Exit fullscreen mode

For example, after one flip of the column [0], we can get 2 rows are satisfied, so we can considering they are the same pattern.

01 -> 01
10 -> 01 (Normalized)
Enter fullscreen mode Exit fullscreen mode

To Count the appearance

We can use hash map to do the work, pattern as the key and count as the value.

// Routine 1st
01 -> [0, 1] -> [[0, 1]: 1]
10

// Routine 2st
01 
10 -> [0, 1] -> [[0, 1]: 2]
Enter fullscreen mode Exit fullscreen mode

Code

class Solution {
    func maxEqualRowsAfterFlips(_ matrix: [[Int]]) -> Int {
        // [pattern: count]
        var map = [[Int]: Int]()

        for row in matrix {
            let base = row[0]
            let pattern = row.map { $0 == base ? 0 : 1 }
            map[pattern, default: 0] += 1
        }

        return map.values.max() ?? 0
    }
}
Enter fullscreen mode Exit fullscreen mode

End of the post

That's it!

Please leave comment if you have any comments, thanks for your reading!

Top comments (0)