【发布时间】:2018-11-29 16:05:44
【问题描述】:
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
太乱了
问题:
如何减少它的运行时间?目前,我正在使用数组。
【问题讨论】:
-
我的猜测是 StackOverflow 不是此类问题的正确平台。此外,没有描述此代码的作用。我想它会更适合CodeReview
-
嵌套循环太多.. 你至少可以摆脱 Index 方法并使用内置的 Array.IndexOf stackoverflow.com/a/6316165/10634638 stackoverflow.com/a/6316165/10634638
标签: c# .net c#-4.0 visual-studio-2015