我想读取每一行输入,将数字存储在 int[] 数组中,执行一些计算,然后尽快移至下一行输入。
输入(标准输入)
2 4 8
15 10 5
12 14 3999 -284 -71
0 -213 18 4 2
0
这是一个纯粹的优化问题,在现实世界中并不完全是良好的实践,因为我假设输入是完美的。我对如何改进当前从 stdin 获取输入并将其表示为整数数组的方法感兴趣。我见过使用扫描仪的方法,其中使用 getnextint 方法,但是我在多个地方读到扫描仪比 BufferedReader 慢很多。
这个接受输入的步骤可以改进吗?
当前方法
BufferedReader bufferedInput = new BufferedReader(new InputStreamReader(System.in));
String line;
String[] lineArray;
try{
// a line with just "0" indicates end of std input
while((line = bufferedInput.readLine()) != "0"){
lineArray = line.split("\\s+"); // is "\\s+" the optimized regex
int arrlength = lineArray.length;
int[] lineInt = new int[arrlength];
for(int i = 0; i < arrlength; i++){
lineInt[i] = Integer.parseInt(lineArray[i]);
}
// Preform some operations on lineInt, then regenerate a new
// lineInt with inputs from next line of stdin
}
}catch(IOException e){
}
从其他问题来看Difference between parseInt and valueOf in java? parseint 似乎是将字符串转换为整数的最有效方法 1 。任何启发都会有很大帮助。
谢谢:)
编辑1:删除GCD信息和“算法”标签
编辑2:(希望)使问题更加简洁,语法更正
最佳答案
首先,我只想指出,在您的特定示例中进行优化是完全没有意义的。
对于您的示例,大多数人都会同意最佳解决方案并不是最佳解决方案。相反,最具可读性的解决方案将是最好的。
<小时/>话虽如此,如果你想要最优的解决方案,那就不要使用 Scanner
,不要使用BufferedReader.readLine()
,不要使用String.split
并且不要使用Integer.parseInt(...)
.
使用 BufferedReader.read()
一次读取一个字符并将它们解析并转换为 int
用手。您还需要实现自己的“可扩展数组 int
”类型,其行为类似于 ArrayList<Integer>
.
这是大量(不必要的)工作,并且需要维护更多行代码。坏主意...
关于java - 优化 - 将 std 输入转换为 java 中的整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37117079/