参考 1007. 行相等的最少多米诺旋转,难度分1541。
题目
在一排多米诺骨牌中,tops[i] 和 bottoms[i] 分别代表第 i 个多米诺骨牌的上半部分和下半部分。(一个多米诺是两个从 1 到 6 的数字同列平铺形成的 —— 该平铺的每一半上都有一个数字。)
我们可以旋转第 i 张多米诺,使得 tops[i] 和 bottoms[i] 的值交换。
返回能使 tops 中所有值或者 bottoms 中所有值都相同的最小旋转次数。
如果无法做到,返回 -1.

示例一
示例 1:输入:tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
输出:2
解释: 图一表示:在我们旋转之前, tops 和 bottoms 给出的多米诺牌。 如果我们旋转第二个和第四个多米诺骨牌,我们可以使上面一行中的每个值都等于 2,如图二所示。
示例 2:
输出:-1
解释: 在这种情况下,不可能旋转多米诺牌使一行的值相等。
解题思路
- 遍历找任意一张的两个点数:要满足题目条件每张多米诺上都会含有相同的一个元素,不妨取第一张多米诺上的两个点数作为两个目标进行查找,若找到第一个目标则返回,未找到则继续找第二个目标,都未找到返回-1。
遍历 3ms
class Solution {
public int minDominoRotations(int[] tops, int[] bottoms) {
//如果能达到满足条件(tops或bottoms都相同)则每张多米诺必含相同数字
//假设是第一张卡牌的上数字
int target = tops[0];
boolean flag = true;
int tCount = 0,bCount = 0;
for(int i = 0; i < tops.length; i++) {
if(tops[i] != target && bottoms[i] != target){
flag = false;
break;
} else {
if(tops[i] == target) tCount ++;
if(bottoms[i] == target) bCount ++;
}
}
if(flag) return tops.length - Math.max(tCount,bCount);
target = bottoms[0];
flag = true;
tCount = 0;
bCount = 0;
for(int i = 0; i < tops.length; i++) {
if(tops[i] != target && bottoms[i] != target){
flag = false;
break;
}else {
if(tops[i] == target) tCount ++;
if(bottoms[i] == target) bCount ++;
}
}
if(flag) return tops.length - Math.max(tCount,bCount);
return -1;
}
}
复杂度分析
- 时间复杂度:
O(n),最多两次循环遍历复杂度O(n)。 - 空间复杂度:
O(1),只使用常量个变量。