繁体   English   中英

如何解决由于Java超时而终止的问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM