Leetcode_1_Array_299_Bulls and Cows

本文介绍了一种高效算法,用于解决猜数字游戏中的牛和奶牛问题。通过将字符串转换为字典和集合的组合,算法巧妙地计算出A和B的数量,避免了时间限制超时的问题。

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

在我自己的不断Debug下,好不容易写出来一个版本,然而Time Limit Exceeded~~~

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        str_secret=list(secret)
        str_guess=list(guess)
        count_A=0
        a=[]
        b=[]
        count_B=0
        for i in range(len(str_secret)):
            if str_secret[i]==str_guess[i]:
                    count_A+=1
                    a.append(i)
                    b.append(i)
        for i in range(len(str_secret)):
            if i not in a:
                for j in range(len(str_guess)):
                     if str_secret[i]==str_guess[j]:
                        if j not in b:
                            count_B+=1
                            b.append(j)
                            break
        return str(count_A)+'A'+str(count_B)+'B'

 

正确版本:

Key::思路非常巧妙,巧妙使用dict和set的组合,将secret和guess分别变成以下格式:

        secret: {'0':{位置索引1,位置索引2},'1':{},'2':{},'3':{},........'9':{}}

        guess: {'0':{位置索引1,位置索引2},'1':{},'2':{},'3':{},........'9':{}}

 

Code:

class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        sc={}
        gc={}
        for i in range(10):
            sc[str(i)]=set()
            gc[str(i)]=set()
        for i in range(len(secret)):
            sc[secret[i]].add(i)
            gc[guess[i]].add(i)
        count_A=0
        count_B=0
        for i in range(10):
            temp=len(sc[str(i)].intersection(gc[str(i)]))
            count_A +=temp
            count_B +=min(len(sc[str(i)]),len(gc[str(i)]))-temp
        return str(count_A)+'A'+str(count_B)+'B'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值