[英]How to solve this terminated due to timeout in Java
Can I get this problem of Terminated due to time out solved? 我可以解决由于超时而终止的问题吗?
I mean how to reduce the complexity or unwanted code in order to solve the issue? 我的意思是如何降低复杂性或不需要的代码以解决问题?
Here is my code: 这是我的代码:
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
Since I don't know the problem statement, the only thing which I can suggest is to always avoid Bubble Sort . 由于我不知道问题陈述,因此我只能建议始终避免使用Bubble Sort 。 It's complexity is
O(n^2)
, and probably that's what hindering you're time requirement. 它的复杂度为
O(n^2)
,这可能是阻碍您需要时间的原因。
Use Arrays.sort
like Arrays.sort(h)
像
Arrays.sort(h)
一样使用Arrays.sort
The only problem I can see is you need to import the scanner before you can use it. 我看到的唯一问题是,您需要先导入扫描仪,然后才能使用它。 When I ran the code you provided it gave me a timeout because it couldn't locate the scanner, but when I imported the scanner it ran just fine, so I'm assuming that's the same timeout error you're getting.
当我运行您提供的代码时,由于找不到扫描仪,它给了我一个超时,但是当我导入扫描仪时,它运行得很好,所以我假设这与您遇到的超时错误相同。 Put this statement at the beginning of your code:
将此语句放在代码的开头:
import java.util.Scanner;
The finished code should look like this: 完成的代码应如下所示:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.