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

程序员面试金典——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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值