3ms C++ use vector as map


  • 0
    H

    In the first loop, count the occurrence of each number in secret and count bulls. In second loop, calculate total correctly guessed count. Finally, cows = total - bulls.

    class Solution {
    public:
        string getHint(string secret, string guess) {
            vector<int> v(10, 0);
            int bull = 0;
            for (int i = 0; i < secret.size(); i++) {
                v[secret[i]-'0']++;
                if (i < guess.size() && secret[i] == guess[i]) bull++;
            }
            int cow = -bull;
            for (int i = 0; i < guess.size(); i++) {
                if (v[guess[i]-'0']-- > 0) cow++;
            }
            return to_string(bull) + "A" + to_string(cow) + "B";
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.