【问题标题】:What is the efficient algorithm to implement Stack?什么是实现 Stack 的有效算法?
【发布时间】:2017-03-12 07:51:59
【问题描述】:

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

输入

输入文件的第一行包含一个整数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

【问题讨论】:

  • 栈没问题。问题出在 IO 的某个地方。也许扫描仪很慢?一开始你可以开始存储字符串,而不是在那里和回来转换整数。
  • 尝试类似于 C++ STL 的 Java 集合。只需 google 即可
  • @Antonin,您是否建议使用 String[] 数组而不是 int[] ?我也尝试过。
  • @NeoR, In Java Stack 集合在那里,但它也让我超时。
  • 好吧,分析一下。在你的代码中加入时间戳并找出瓶颈

标签: algorithm performance stack


【解决方案1】:

经验法则:如果您要解决竞争性编程风格问题并且输入很大(例如,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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 2021-01-21
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多