leetcode1072

1 import collections
2 
3 class Solution:
4     def maxEqualRowsAfterFlips(self, A):
5         return max(collections.Counter(tuple(x ^ r[0] for x in r) for r in A).values())

参考:https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/303752/Python-1-Line

1行代码的风格,很Pythonic,执行效率还很高,我只想说——AWSL。

 1 import collections
 2 
 3 class Solution:
 4     def maxEqualRowsAfterFlips(self, matrix):
 5         cache = collections.defaultdict(int)
 6         for row in matrix:
 7             vals = []
 8             trans = []
 9             for c in row:
10                 vals.append(c)
11                 trans.append(1 - c)
12             cache[str(vals)] += 1
13             cache[str(trans)] += 1
14         return max(cache.values())

参考:https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/303891/Simple-Python

这个python版本与下面的java版本思路是一样的,我在java版中写了注释,就不再赘述了。 

 1 public class Solution {
 2     public int maxEqualRowsAfterFlips(int[][] matrix) {
 3         int ans = 0;
 4         int m = matrix.length;//
 5         int n = matrix[0].length;//
 6         int[] flip = new int[n];
 7         for(int i = 0; i < m; i++) {
 8             int cnt = 0;
 9             for(int j = 0; j < n; j++){ 
10                 flip[j] = 1 - matrix[i][j];//存储将当前第i行所有元素flip后的数组
11             }
12             for(int k = 0; k < m; k++) {
13                 //如何发现与当前行"完全一样"的行或者"完全不同"的行,那就是可以通过列反转达到"行元素都相同"效果的行
14                 if(Arrays.equals(matrix[k], matrix[i]) || Arrays.equals(matrix[k], flip)){ 
15                     cnt++;
16                 }
17             }
18             //每次选择当前行为"基准"计算一个可以根据此基准得到的同元素数行的数量
19             //遍历所有行,保留最大的一种计算结果
20             ans = Math.max(ans, cnt);
21         }
22         return ans;
23     }
24 }

参考:https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/303897/Java-easy-solution-%2B-explanation

第三个方案(java的)中原帖子举的例子有点问题,不知道以后题主会不会更正,在此提示一下,如图:

这个红色行(即4th row)应该为[0,1,1,0,1],而本例应该得到的结果是3。

如果按照图中的数据,最后的结果是2。因此我猜测作者是写错了示例的数据。

原文地址:https://www.cnblogs.com/asenyang/p/10963249.html