[英]Circular Array Rotation Time Limit Exceeded(TLE)
我真的很困惑为什么我的 Java 代码不起作用它在 Hacker Earth 上的 Code Monks 上给出了 TLE。 这是问题的链接 -链接到问题第一个问题僧侣和旋转
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(--t>0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
我不知道为什么它会给 TLE 我认为有一些无限循环。
该网站的问题是-
Monk 和 Rotation Monk 喜欢对数组进行不同的操作,因此作为 HackerEarth School 的校长,他为他的新学生 Mishki 分配了一项任务。 Mishki 将获得一个大小为 N 的整数数组 A 和一个整数 K ,她需要将数组以正确的方向旋转 K 步,然后打印结果数组。 由于她是新来的学校,请帮助她完成任务。
输入:第一行将由一个整数 T 组成,表示测试用例的数量。 对于每个测试用例:
约束:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
样本输入
1
5 2
1 2 3 4 5
样本输出
4 5 1 2 3
解释
这里 T 是 1,这意味着一个测试用例。
表示数组中元素的数量,表示旋转的步数。
初始数组是:在第一次旋转中,5 将位于第一个位置,所有其他元素将从当前位置移动到一个位置。 现在,结果数组将是
在第二次旋转中,4 将进入第一个位置,所有其他元素将从当前位置移动到一个位置。 现在,结果数组将是
时间限制:每个输入文件 1.0 秒内存限制:256 MB 源限制:1024 KB
问题在这里
for(int i=0;i<n-k;i++) //this loop you are using for storing input elements in array
ar[i]=in.nextInt();
for(int i=0;i<k;i++) // here you again taking the input you don't need this loop
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
您还需要将 while 循环中的条件while(--t>0)
更改为while(--t >= 0)
。 它应该>= 0
否则它将不起作用。 其他解决方案是使用 post decrement while(t-- > 0)
您正在尝试打印阵列的右旋转。 所以你需要从索引n - k
开始打印元素。 然后你需要计算结束索引它是(n - k) + n
这是因为数组有n
元素。 然后你可以访问这样的数组元素arr[i % n]
。
这是完整的工作解决方案
class TestClass {
static int[] ar = new int[100001];
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
byte t = in.nextByte();
while (--t >= 0) {
int n = in.nextInt();
int k = in.nextInt() % n;
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
for (int i = n - k; i < n + (n - k); i++)
System.out.print(ar[i % n] + " ");
System.out.println();
}
}
}
从不同的角度思考。 我们可以应用不同的逻辑,而不是拆分字符串并将其转换为数组并应用迭代逻辑。
诀窍是你只需要找到我们只需要拆分一次的输入字符串的位置。 我的意思是,
输入=>
6 2 //4是数字的长度,2是旋转的索引
1 2 3 4 5 6 //数组(使用缓冲读取器将输入作为字符串)
在这里,我们只需要在倒数第二个空格,即第四个空格处拆分数组字符串。 因此,只需将字符串拆分一次即可实现输出-
5 6 1 2 3 4
第一次分裂 - 5 6 + 空格 + 第二次分裂 - 1 2 3 4
这个逻辑对我有用,所有的测试用例都通过了。
当数组输入字符串只是一个数字时,也不要忘记涵盖极端情况。
代码片段-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.