4ms c++ solution


  • 0
    E
    string getHint(string secret, string guess) {
            int size = secret.size();
            int bulls = 0;
            int cows = 0;
            
            int sM[10] = { 0 };
            int gM[10] = { 0 };
            
            for(int i=0; i<size; i++)
            {
                if(secret[i] == guess[i])
                    bulls++;
                  
                sM[secret[i] - '/'-1]++;  
                gM[guess[i] - '/'-1]++; 
            }
            
            for(int i=0; i<10; i++)
            {
                cows = cows + ( (sM[i]>gM[i])? gM[i] : sM[i] );
            }
            cows = cows-bulls;
            return to_string(bulls) + "A" + to_string(cows) + "B";
        }
    

    In one pass, code counts bulls and occurrence of each digit for secret and guess. The counts are kept in an array of 10 (since there can be at most 10 digits). Then for each digit, selects the small number of occurrence (since small number gives cow count) and sums for all digits. At the end, bull number is subtracted from cow number since cow number includes the bull number with this method.
    I first use hash map to keep the digit counts, but with hash map it took 131ms. After converting hash map to array, time decreased to 4ms.


Log in to reply
 

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