程序员面试金典——17.5珠玑妙算

本文详细解析了一种猜数字游戏的算法实现,通过统计“猜中”与“伪猜中”的数量来判断猜测的准确性。文章提供了一个具体的C++代码示例,包括如何计算猜中的数字数量以及如何确定伪猜中的数量。

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

程序员面试金典——17.5珠玑妙算

参考网址:https://www.nowcoder.com/profile/2708949/codeBookDetail?submissionId=13283364
Solution1:算法
从题目中可以获取隐含信息:
“猜中” 属于 “伪猜中”,但是反过来不成立。
所有需要先统计猜中,
然后再统计伪猜中个数= 可能的伪猜中个数 - 猜中个数
因此代码就比较容易写出来。

class Result {
public:
    vector<int> calcResult(string A, string guess) {
        // write code here
        int n1 = 0, n2 = 0;//n1是猜中,n2是伪猜中
        map<char, int> arr1, arr2;
        vector<int> res;
        for (int i = 0; i < 4; ++i) {
            ++arr1[A[i]];
            ++arr2[guess[i]];
            if(A[i] == guess[i])
                ++n1;//统计猜中的次数
        }
        //int s = A[i].size() < B.size() ? A.size(),B.size();

        for (auto it = arr2.begin(); it != arr2.end(); ++it) {
            if (A.find(it->first) != string::npos && it->second > 0) {
                if(it->second < arr1[it->first])
                    n2 += it->second;
                else
                    n2 += arr1[it->first];
                //++n2;
                //--(it->second);
            }
        }
        n2 = n2 - n1;
        res.push_back(n1);
        res.push_back(n2);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值