【PAT】超时问题及处理方案(改进输入输出)
Pat考试中,很多题目都是需要读取大量的数据,而java的Scanner对于读取大量数据效率低,如果选择不当,即使算法写的再好,也是无功而返,读取数据时间超时已经gg了
1、一般情况下用BufferedReader类读取数据即可,尽量避免使用scanner2、数据量大,而且都是相同类型数据,可以考虑使用StreamTokenizer封装BufferedReader效率更好
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static int nextInt()throws IOException {in.nextToken();return (int)in.nval;}
快读:
-
用BufferReader类和StringTokenizer类代替Scanner类来读取输入,读取输入的语法如下:
- 读double&int
import java.io.*; public class test { public static void main(String args[]) throws IOException{ StreamTokenizer re = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); re.nextToken(); int n = (int)re.nval; System.out.println(n); } }
-
读字符(当我们读字符串的时候我们就不需要加StreamTokenizer类)
import java.io.*; public class test { public static void main(String args[]) throws IOException{ // StreamTokenizer re = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); String x = re.readLine(); System.out.println(x); } }
-
两者都有
import java.io.*; public class test { public static void main(String args[]) throws IOException{ BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer r = new StreamTokenizer(re); r.nextToken(); int n = (int)r.nval; String x = re.readLine(); System.out.println(n+" "+x); // 输入 // 3 // afadfa // 输出 // 3 } }
注意!:我们想的是 读入一个整数,然后读入一个字符串,可是我们这里只读入了这个整数。这个是因为我们读入整数的时候,把整数读走了,但是整数后面的回车并没有读走,我们如果直接使用readLine()来读的话 就会读不到下一行的字符串 所以这里我们应该在加一个readLine()来读掉那个回车
原文链接:https://blog.csdn.net/shizhuba/article/details/105068631
快速输出:
数据大的时候用这种方法读入数据,这个输入也比System的那个输出要快。所以我们以后写数据大的程序时,可以这样写
import java.io.*;
public class test {
public static void main(String args[]) throws IOException{
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer r = new StreamTokenizer(re);
PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
r.nextToken(); int n = (int)r.nval;
re.readLine();
String x = re.readLine();
pr.println(n+" "+x);
pr.flush();
}
}
//使用PrintWriter输出时 记得最后加个flush()