Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java UVa在线法官#超过458时限_Java_Performance_Algorithm - Fatal编程技术网

Java UVa在线法官#超过458时限

Java UVa在线法官#超过458时限,java,performance,algorithm,Java,Performance,Algorithm,我正在尝试解决这个问题,并提出了以下算法,该算法为样本输入数据提供了正确的输出,但运行时间超过了允许的时间 public class Decoder { public void decoder() { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String line = sc.nextLine(); for (int

我正在尝试解决这个问题,并提出了以下算法,该算法为样本输入数据提供了正确的输出,但运行时间超过了允许的时间

    public class Decoder {

    public void decoder() {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {

            String line = sc.nextLine();

            for (int i = 0; i < line.length(); i++) {

                if(line.charAt(i)>=32 && line.charAt(i)<=126)
                System.out.print((char) (line.charAt(i) - 7));

            }
            System.out.println();
        }
    }

}
公共类解码器{
公共空解码器(){
扫描仪sc=新的扫描仪(System.in);
while(sc.hasNext()){
字符串行=sc.nextLine();
对于(int i=0;i=32&&line.charAt(i)
  • 避免将流解码为字符。如果只需要支持ASCII,则可以使用字节

  • 读取和写入大块数据,以避免函数/系统调用开销

  • 避免不必要的分配。当前您正在为每行分配新字符串

  • 不要将输入拆分为行,以避免非常小的行的性能不佳

  • 例如:

    public static void main(String[] args) throws IOException {
        byte[] buffer = new byte[2048];
        while (true) {
            int len = System.in.read(buffer);
            if (len <= 0) {
                break;
            }
            for (int i = 0; i < len; i++) {
                ...
            }
            System.out.write(buffer, 0, len);
        }
    }
    
    publicstaticvoidmain(字符串[]args)引发IOException{
    字节[]缓冲区=新字节[2048];
    while(true){
    int len=系统in.读取(缓冲区);
    
    如果(len永远不要使用
    扫描仪
    进行长输入。扫描仪比Java中读取输入的其他方法(如
    BufferedReader
    )慢得令人难以置信。这个UVa问题看起来像是输入很长的问题。

    也许处理整行,然后打印它会比解码和打印每个字符更快另外。你确定你生成了正确的输出-这就是你的程序失败的真正原因,对吗?我问的原因是你不仅将更改值限制为ASCII可打印字符,而且还将打印限制为ASCII可打印字符,减7。如果结果在e正确的范围?@Patrick87它超出了时间限制答案正确嘿,代码真的很有趣,但我不确定它到底在做什么。所以你基本上是将字节数组设置为(是什么让你选择2048的最大值?)然后你读了缓冲区大小的系统?我玩过它,它工作得很好,但我不知道怎么做?@LuiggiMendoza我怎样才能添加新行?