gpt4 book ai didi

c# Hackerrank 代码因超时而终止,但没有办法进一步优化此代码?

转载 作者:行者123 更新时间:2023-11-30 20:33:02 24 4
gpt4 key购买 nike

我当时正在用 C# 进行黑客排名挑战,试图将我的一些 C 技能带到 C# 中。现在我知道 hacker rank 因超时而杀死程序是出了名的愚蠢(在这种情况下,如果它持续超过 3 秒)。但老实说,我想不出进一步优化这段代码的方法。

说明如下: https://www.hackerrank.com/challenges/ctci-array-left-rotation

基本上,挑战是将数字数组在数组内向左移动 x 次。

据我所知,这段代码是尽可能少的,但仍然可以完成他们要求的事情。我认为进一步优化此代码的唯一方法是将约束“if(a[i] > 1000000 || a[i] < 1 )”与代码末尾的 writeline forloop 合并,但我试过了它没有用。

对我来说,这实际上是将数组移动 x 的最少操作次数。但由于超时,代码在测试用例 7 和 8(共 8 个)中失败。我错过了什么吗?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution

{

static void Main(String[] args) 

{
int i, j;
int temp = 0;
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);

//constraints
if(n >= 100000 || n < 1 )
{
System.Environment.Exit(1);
}

if(k > n || n < 1 )
{
System.Environment.Exit(1);
}

for(i = 0; i< n; i++)
{
if(a[i] > 1000000 || a[i] < 1 )
{
System.Environment.Exit(1);
}
}

//double for loop. one adjust position by one. then repeat k number of times.

for(j = 0; j<k; j++)
{

for(i = 0; i< n-1; i++)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}

//view array
for(i = 0; i< n; i++)
{
Console.Write(a[i] + " " );
}

}

最佳答案

我使用了一个队列机制来让它工作。这样您就不必进行任何数组复制,只需将字符串旋转到末尾即可。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

static int[] leftRotation(int[] arr, int rotation) {
Queue<int> queue = new Queue<int>(arr);

for (int i = 0; i < rotation; i++)
{
queue.Enqueue(queue.Dequeue());
}

return queue.ToArray();
}

static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int d = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
int[] result = leftRotation(a, d);
Console.WriteLine(String.Join(" ", result));
}
}

关于c# Hackerrank 代码因超时而终止,但没有办法进一步优化此代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40715901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com