题目如下:

解题思路:把matrix任意一行的的所有元素拼成一个字符串,例如0010110,要把这行变成全是0或者全是1,那么要经过4次或者3次的列变换。变换之后,很显然matrix中字符串为0010110或者1101001的行最后也会变成全为0或者全为1。因此题目就变成了找出matrix中的某一行,使得在整个matrix中和这行相等的行或者相反的行的最多(即0对应1,1对应0的行)。怎么求出最大值的呢?并查集很适合这个场景。

代码如下:

class Solution(object):
def maxEqualRowsAfterFlips(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
parent = [i for i in range(len(matrix))] def find(v1):
p1 = parent[v1]
if p1 != v1:
return find(p1)
return p1 def union(v1,v2):
p1 = find(v1)
p2 = find(v2)
if p1 <= p2:
parent[v2] = p1
else: parent[v1] = p2
def toString(l1):
new_l1 = map(lambda x: str(x), l1)
return ''.join(new_l1) row = []
row_inverse = []
for i in range(len(matrix)):
row.append(toString(matrix[i]))
v1_inverse = ''
for k in row[i]:
v1_inverse += '' if k == '' else ''
row_inverse.append(v1_inverse) for i in range(len(matrix)):
v1 = row[i]
v1_inverse = row_inverse[i]
for j in range(i+1,len(matrix)):
v2 = row[j]
if v1 == v2 or v1_inverse == v2:
union(i,j) dic = {}
res = 0
for i in range(len(matrix)):
p = find(i)
dic[p] = dic.setdefault(p,0) + 1
res = max(res,dic[p]) return res
05-11 22:37