Problem
- https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows
- https://leetcode.cn/problems/flip-columns-for-maximum-number-of-equal-rows (δΈζ)
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)
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)
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]
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
}
}
End of the post
That's it!
Please leave comment if you have any comments, thanks for your reading!
Top comments (0)