# 1007. Minimum Domino Rotations For Equal Row

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/

> 内容描述

```
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino.  (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the i-th domino, so that A[i] and B[i] swap values.

Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.

If it cannot be done, return -1.

 

Example 1:



Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation: 
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:

Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation: 
In this case, it is not possible to rotate the dominoes to make one row of values equal.
 

Note:

1 <= A[i], B[i] <= 6
2 <= A.length == B.length <= 20000
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

两种可能：
1. 全部一样的数字就是A[0]
2. 全部一样的数字就是B[0]

其中每种可能又分为两种：
1. 最终返回A，即最终全部相同的数字都在A
2. 最终返回B，即最终全部相同的数字都在B

```python
class Solution:
    def minDominoRotations(self, A: List[int], B: List[int]) -> int:
        flag1 = all(A[i] == A[0] or B[i] == A[0] for i in range(1, len(A)))
        flag2 = all(A[i] == B[0] or B[i] == B[0] for i in range(1, len(A)))

        if not flag1 and not flag2:
            return -1
        
        cnt1, cnt2 = collections.Counter(A), collections.Counter(B)
        if flag1 and flag2:
            return len(A) - max(cnt1[A[0]], cnt1[B[0]], cnt2[A[0]], cnt2[B[0]])
        elif flag1 and not flag2:
            return len(A) - max(cnt1[A[0]], cnt2[A[0]])
        else:
            return len(A) - max(cnt1[B[0]], cnt2[B[0]])
```



























