c# - 新年混沌HackerRank练习题-C#解法优化
问题描述
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);
}
除了挑战提供的方法之外,您不需要任何其他方法
推荐阅读
- python - 在 rasa_nlu 提到它缺少依赖项后安装 sklearn_crfsuite 的问题
- reactjs - 快照测试..期望(testRenderer)与期望(testRender.toJSON)
- python - 使用诗歌从 conda-forge(例如 cartopy)安装预构建包,而不依赖 conda(仅使用通道)
- r - 如何计算每列的值> x的时间比例
- xamarin.ios - Xamarin IOS CoreML 模型更改多路器 (posenet)
- ruby - ruby rspec 单元测试中的 OpenSSL 版本号错误,连接到 docker hashcorp vault
- javascript - 加载视频时如何添加微调器?使用 Javascript
- r - 如何合并多个变量并使其中一个变量处于模糊匹配中
- javascript - 如何在jquery中的ajax加载数据中传递全局变量数据?
- python - 如何使散点图中的点尺寸逐渐减小(matplotlib)