为什么BufferedReader在Java中比Scanner类更高效?

huangapple go评论90阅读模式
英文:

Why bufferedReader is much efficient than Scanner class in java?

问题

请看以下问题,无论您如何高效地编写此问题的解决方案,使用Scanner类都会导致超时。

问题:

已经给定一个包含n个元素的数组。现在对于给定的查询,您提供了一个整数,您必须找到最小和,该和是所有值小于查询中提供的给定整数的数组中所有元素的和。

输入格式:

第一行:一个整数,表示数组元素的数量。
第二行:以空格分隔的整数,表示数组元素。
第三行:一个整数,表示查询数量。
对于每个查询:一个新行包含一个整数。

输出格式:
对于每个查询,以新行打印一个整数,即最小和。

仅通过使用“Buffered Reader”替代“Scanner类”和使用“Buffered Writer”替代“System.out.print”,可以使此代码的速度提高一倍,并且所有测试用例都可以轻松通过,其背后的原因是什么?

英文:

Have a look in the following question , no matter how much efficiently you write the solution for this , using Scanner class is resulting in the time out .

Question :

You have given an array , having  elements . Now for given  query you have provided an integer  and you have to find the Min Sum that is the sum of all elements in the array whose value less than the given integer provided into query.

Input format:

First line: An integer  denoting number of array elements.
Second line:  space seperated integer denoting array elements.
Third line: An integer  denoting number of query.
For each query: A new line contain an integer 

Output format:
For each query print a single integer that is Min Sum in a new line.

Just by using Buffered Reader instead of Scanner class and Buffered Writer instead of System.out.print , makes this code twice as faster and all the test cases passes easily , what is the reason behind this ?

答案1

得分: 1

BufferedReader比Scanner快得多,因为它具有比Scanner更大的缓冲内存。您可以在此讨论中看到这两者之间的区别。

英文:

BufferedReader is significantly faster than Scanner as it has a larger buffer memory than Scanner. You can see the difference between the two in this discussion.

huangapple
  • 本文由 发表于 2020年4月10日 16:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61136644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定