web-dev-qa-db-fra.com

Optimisation du code HackerRank du Nouvel An

static void minimumBribes(int[] q)
{
    Int32 TotalCount = 0;
    bool blnSuccess = true;
    Int32[] size = Ordering(q);
    for (int intI = 0; intI < q.Length; intI++)
    {
        Int32 Tempvariable = 0;
        Int32 TooChaotic = 0;
        Int32 index = Index(size,q[intI]);
        do
        {
            if (q[intI] != size[intI])
            {
                Tempvariable = size[index];
                size[index] = size[index - 1];
                size[index - 1] = Tempvariable;
                index = index - 1;
                TooChaotic = TooChaotic + 1;
                if (TooChaotic > 2)
                {
                    break;
                }
                TotalCount = TotalCount + 1;
            }
        } while (q[intI] != size[intI]);
        if (TooChaotic > 2)
        {
            Console.WriteLine("Too chaotic");
            blnSuccess = false;
            break;
        }
    }
    if (blnSuccess)
    {
        Console.WriteLine(TotalCount);
    }
}

static int[] Ordering(int[] z)
{
    int[] r = new int[z.Length];
    r = z.OrderBy(x => x).ToArray();
    return r;
}
static int Index(int[] z,int integer)
{
    for (int intI = 0; intI < z.Length; intI++)
    {
        if(z[intI]== integer)
        {
            return intI;
        }
    }
    return 0;
}

Ce code fonctionne bien, mais son exécution est trop longue. Je reçois "Terminé en raison de l'expiration du délai" dans HackerRank. Cependant, la solution fonctionne bien sur l'ordinateur local mais prend plus de temps. Problème lié: https://www.hackerrank.com/challenges/new-year-chaos/problem .

Exemple d'entrée

2 (the number of test cases)

5 (number of people in the queue)

2 1 5 3 4 (n nombres entiers séparés par des espaces décrivant l'état final de la file d'attente)

5 (number of people in the queue)

2 5 1 3 4 (n entiers séparés par des espaces décrivant l'état final de la file d'attente).

Il doit imprimer un entier représentant le nombre minimum de pots de vin nécessaires, ou trop chaotique si la configuration de la ligne n'est pas possible.

Sortie 3

Trop chaotique

Question:

Comment puis-je réduire son temps d'exécution? Actuellement, j'utilise un tableau.

1
Ramakrishna

Je l'ai résolu il y a quelques semaines, c'est ma solution au problème (100%)

static void minimumBribes(int[] q) {
    int bribe = 0;
    bool chaotic = false;
    int n = q.Length;
    for(int i = 0; i < n; i++)
    {
        if(q[i]-(i+1) > 2)
        {               
            chaotic = true;
            break;     
        }
        for (int j = Math.Max(0, q[i]-1-1); j < i; j++)
            if (q[j] > q[i]) 
                bribe++;
    }
    if(chaotic)
        Console.WriteLine("Too chaotic");
    else
        Console.WriteLine(bribe);
}

Vous n'avez besoin d'aucune autre méthode que celle fournie par le défi

5
Gianlucca