LeetCode 1007. Minimum Domino Rotations For Equal Row
考点 | 难度 |
---|---|
Greedy | Easy |
题目
In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
思路
记录A和B里数字出现次数和A[i] == B[i]的个数。如果countA[i] + countB[i] - same[i] != A.length,无解,返回-1.其他情况返回countA[i] - same[i]和countB[i] - same[i]里更小的,也就是min(countA[i], countB[i]) - same[i]。
答案
from collections import Counter
class Solution:
def minDominoRotations(self, A, B):
if len(A) != len(B): return -1
same, countA, countB = Counter(), Counter(A), Counter(B)
for a, b in zip(A, B):
if a == b:
same[a] += 1
for i in range(1, 7):
if countA[i] + countB[i] - same[i] == len(A):
return min(countA[i], countB[i]) - same[i]
return -1