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;
}
此代码可以正常工作,但是其运行时间太长。我在HackerRank中收到“由于超时而终止”。但是,该解决方案在本地计算机上运行良好,但是需要更多时间。问题链接:https://www.hackerrank.com/challenges/new-year-chaos/problem。
样本输入
2(测试用例数)
5(队列中的人数)
2 1 5 3 4(n个用空格分隔的整数描述队列的最终状态)
5(队列中的人数)
2 5 1 3 4(n用空格分隔的整数描述队列的最终状态)。
它必须打印一个整数,代表所需的最小贿赂数,如果无法进行线路配置,则太混乱。
输出3
太混乱
问题:
如何减少其运行时间?目前,我正在使用数组。
几周前我已经解决了,这是我的解决方案(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]-2); j < i; j++)
if (q[j] > q[i])
bribe++;
}
if(chaotic)
Console.WriteLine("Too chaotic");
else
Console.WriteLine(bribe);
}
除了挑战所提供的方法之外,您不需要任何其他方法