★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/ )
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-uoarwdma-mb.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a matrix
consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.git
Return the maximum number of rows that have all values equal after some number of flips.github
Example 1:微信
Input: [[0,1],[1,1]]
Output: 1 Explanation: After flipping no values, 1 row has all values equal.
Example 2:app
Input: [[0,1],[1,0]]
Output: 2 Explanation: After flipping values in the first column, both rows have equal values.
Example 3:spa
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:code
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
matrix[i].length
's are equalmatrix[i][j]
is 0
or 1
給定由若干 0 和 1 組成的矩陣 matrix
,從中選出任意數量的列並翻轉其上的 每一個 單元格。翻轉後,單元格的值從 0 變成 1,或者從 1 變爲 0 。htm
返回通過一些翻轉後,行上全部值都相等的最大行數。 blog
示例 1:ip
輸入:[[0,1],[1,1]] 輸出:1 解釋:不進行翻轉,有 1 行全部值都相等。
示例 2:
輸入:[[0,1],[1,0]] 輸出:2 解釋:翻轉第一列的值以後,這兩行都由相等的值組成。
示例 3:
輸入:[[0,0,0],[0,0,1],[1,1,0]] 輸出:2 解釋:翻轉前兩列的值以後,後兩行由相等的值組成。
提示:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
matrix[i].length
都相等matrix[i][j]
爲 0
或 1
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 }
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 }