Description
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
.
在一排多米诺骨牌中,A[i]
和 B[i]
分别代表第 i 个多米诺骨牌的上半部分和下半部分。(一个多米诺是两个从 1 到 6 的数字同列平铺形成的 —— 该平铺的每一半上都有一个数字。)
我们可以旋转第 i
张多米诺,使得 A[i]
和 B[i]
的值交换。
返回能使 A
中所有值或者 B
中所有值都相同的最小旋转次数。
如果无法做到,返回 -1
.
题目链接:https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/
Difficulty: medium
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
分析
- 找到AB中点数出现的次数大于等于A(B)的长度的点index,作为后面判断A或者B能否全部相等的判定点数,若没有,返回-1;
- 遍历AB,若A[i]不等于index且B[i]等于index,则计数s1加一,若A[i]B[i]都不等于index,则该种情况不满足;
- 同理再遍历AB,若B[i]不等于index且A[i]等于index,则计数s2加一,若A[i]B[i]都不等于index,则该种情况不满足;
- 若两种情况都不满足,返回-1;若只满足一种情况,返回相应的计数;若都满足,返回最小计数。
参考代码
class Solution(object):
def minDominoRotations(self, A, B):
import collections
li=collections.defaultdict(int)
for a in A:
li[a]+=1
for b in B:
li[b]+=1
index=0
for i in range(len(A)):
if(li[A[i]]>=len(A)):
index=A[i]
s1=0
judge=True
for i in range(len(A)):
if(A[i]!=index):
if(B[i]==index):
s1+=1
else:
judge=False
break
s2=0
for i in range(len(A)):
if(B[i]!=index):
if(A[i]==index):
s2+=1
else:
if(not judge):
return -1
else:
return s1
if(judge):
return min(s1,s2)
return s2