Algorithm 实现堆栈的有效算法是什么?
我遇到了一个问题。我需要用push和pop操作实现堆栈 输入Algorithm 实现堆栈的有效算法是什么?,algorithm,performance,stack,Algorithm,Performance,Stack,我遇到了一个问题。我需要用push和pop操作实现堆栈 输入 输入文件的第一行包含一个整数N(1经验法则:如果您正在解决一个有竞争力的编程风格问题,并且输入量很大(例如,10^5number或更多),那么扫描仪的速度太慢 您可以在BufferedReader上使用StringTokenizer来加速输入 它可以是这样的: class FastScanner { private StringTokenizer tokenizer; private BufferedReader re
输入文件的第一行包含一个整数
N(1经验法则:如果您正在解决一个有竞争力的编程风格问题,并且输入量很大(例如,10^5
number或更多),那么扫描仪的速度太慢
您可以在BufferedReader
上使用StringTokenizer
来加速输入
它可以是这样的:
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
堆栈是好的。问题是IO中的某个地方。也许扫描仪是慢的。首先,你可以开始存储字符串,而不是在那里转换和返回int。尝试类似于C++ STL的java集合。只是谷歌。them@Antonin,是否建议使用字符串[]数组而不是int[]?。我也试过这样做。@NeoR,Java堆栈集合中有,但它也让我超时了。好吧,分析一下。在代码中添加时间戳,找到瓶颈
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("stack.in"));
PrintWriter pw = new PrintWriter(new File("stack.out"));
int n=sc.nextInt();
int[] stack = new int[n]; int i=0;
while(n-->0) {
String s = sc.next();
if(s.equals("+")) {
stack[i++]=sc.nextInt();
} else {
pw.println(stack[--i]);
}
}
sc.close(); pw.close();
}
}
Time limit: 2 seconds
Memory limit: 256 megabytes
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}