[英]How to solve this terminated due to timeout in Java
我可以解決由於超時而終止的問題嗎?
我的意思是如何降低復雜性或不需要的代碼以解決問題?
這是我的代碼:
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);
}
}
由於我不知道問題陳述,因此我只能建議始終避免使用Bubble Sort 。 它的復雜度為O(n^2)
,這可能是阻礙您需要時間的原因。
像Arrays.sort(h)
一樣使用Arrays.sort
我看到的唯一問題是,您需要先導入掃描儀,然后才能使用它。 當我運行您提供的代碼時,由於找不到掃描儀,它給了我一個超時,但是當我導入掃描儀時,它運行得很好,所以我假設這與您遇到的超時錯誤相同。 將此語句放在代碼的開頭:
import java.util.Scanner;
完成的代碼應如下所示:
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.