LeetCode知识点总结 - 1007

文章介绍了如何解决LeetCode问题1007,计算使多米诺骨牌行两端数字相同的最小旋转次数。通过计数每个数字在两行中出现的次数以及相等的数目,判断是否能实现目标并返回最小操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 1007. Minimum Domino Rotations For Equal Row

考点难度
GreedyEasy
题目

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   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值