gpt4 book ai didi

algorithm - 实现 Stack 的有效算法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:06 25 4
gpt4 key购买 nike

我遇到了一个问题。我需要使用推送和弹出操作来实现堆栈。

输入

输入文件的第一行包含一个整数 N (1 <= N <= 10^6) – 测试用例的数量。

接下来的 N 行讲述操作。 +意味着插入。 -意味着流行。我需要打印弹出的元素。

Example
Input Output
6
+ 1 10
+ 10 1234
-
+ 2
+ 1234
-

我写了下面的代码

   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

最佳答案

一条经验法则:如果您正在解决竞争性编程风格问题并且输入很大(例如,10^5 个数字或更多),Scanner太慢了。

您可以在 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());
}
}

关于algorithm - 实现 Stack 的有效算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com