4ms C++ One Array Clean Solution


  • 7
    H
    class Solution {
    public:
        string getHint(string secret, string guess) {
            int map[10] = {0};
            int a = 0, b = 0;
            for (int i = 0; i < guess.size(); ++i) {
                if (guess[i] == secret[i]) ++a;
                ++map[guess[i] - '0'];
            }
            for (int i = 0; i < secret.size(); ++i) {
                if (map[secret[i] - '0']-- > 0) ++b;
            }
            return to_string(a) + "A" + to_string(b - a) + "B";
        }
    };
    

    a stores "bulls" while b stores sum of "bulls" and "cows".

    We only need to build one hash map for "guess". First loop is to build hash map as well as to find "bulls". The second one is to find all "guess" numbers existing in "secret". When there is a match, we reduce the value for this number to handle situation like ("11" "10").

    Time: O(n) Space: O(1)


Log in to reply
 

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