[英]Can i make following code any Faster
我想使以下代碼更快,而無需更改從標准控制台進行的讀取/寫入。 第一行包含輸入數量,隨后的行包含一組Integer
。
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
try {
java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int a = Integer.parseInt(r.readLine());
for (int i = 0; i < a; i++) {
StringTokenizer st = new StringTokenizer(r.readLine());
while (st.hasMoreTokens()) {
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}
您在此處執行了很多多余的自動裝箱和發件箱操作,如果您將first
和second
定義為原始int
而不是java.lang.Integer
包裝器類,則可以節省這些冗余。 但是,我懷疑對於任何合理大小的輸入,您是否都會注意到差異。
這里有一些建議,我不確定這些建議會有很大幫助。
1)這個
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
可以更改為
System.out.println(first < second
? "<"
: first > second
? ">"
: "="
);
2)由於您使用的是throws子句,而try-catch
執行任何操作,因此可以將其刪除。
3)在這里
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
您不是第二次檢查hasMoreTokens()
。
您可以考慮在下面使用BufferedReader
的構造函數:
public BufferedReader(Reader in, int sz)
給sz
參數一個合理的高值 ,可以避免緩沖區太頻繁地重新填充。
附帶說明一下,如果已到達流的末尾,則readLine()
返回null
,但最好在調用new StringTokenizer(r.readLine())
和Integer.parseInt(r.readLine())
之前檢查其返回值。 。
編輯后的類如下:
public class Main {
public static void main(String[] args) {
BufferedReader r;
String line;
StringTokenizer st;
int a, first, second;
r = new BufferedReader(new InputStreamReader(System.in), 4096);
try {
line = r.readLine();
if (line != null) {
a = Integer.parseInt(line);
for (int i = 0; i < a; ++i) {
line = r.readLine();
if (line == null)
break;
st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
first = Integer.parseInt(st.nextToken());
second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
}
r.close();
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.