在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a Return the maximum number of rows that have all values equal after some number of flips. 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.
Note:
给定由若干 0 和 1 组成的矩阵 返回经过一些翻转后,行上所有值都相等的最大行数。 示例 1: 输入:[[0,1],[1,1]] 输出:1 解释:不进行翻转,有 1 行所有值都相等。 示例 2: 输入:[[0,1],[1,0]] 输出:2 解释:翻转第一列的值之后,这两行都由相等的值组成。 示例 3: 输入:[[0,0,0],[0,0,1],[1,1,0]] 输出:2 解释:翻转前两列的值之后,后两行由相等的值组成。 提示:
Runtime: 1508 ms
Memory Usage: 21.3 MB
1 class Solution { 2 func maxEqualRowsAfterFlips(_ matrix: [[Int]]) -> Int { 3 var map:[String:Int] = [String:Int]() 4 for x in matrix 5 { 6 var s:String = String() 7 let flag:Int = x[0] 8 for i in 0..<x.count 9 { 10 if x[i] == flag 11 { 12 s.append("1") 13 } 14 else 15 { 16 s.append("0") 17 } 18 } 19 map[s,default:0] += 1 20 } 21 var result:Int = 0 22 for val in map.values 23 { 24 result = max(result,val) 25 } 26 return result 27 } 28 } 1600ms 1 class Solution { 2 func maxEqualRowsAfterFlips(_ matrix: [[Int]]) -> Int { 3 var patternCountMap = [Int:Int]() 4 let mask = 1 << matrix[0].count - 1 5 return matrix.reduce(0) { 6 let pattern = $1.reduce(0) { $0 << 1 | $1 } & mask 7 if patternCountMap[pattern] != nil { 8 patternCountMap[pattern]! += 1 9 patternCountMap[mask - pattern]! += 1 10 } else { 11 patternCountMap[pattern] = 1 12 patternCountMap[mask - pattern] = 1 13 } 14 return max($0, patternCountMap[pattern]!) 15 } 16 } 17 }
|
请发表评论