【问题标题】:Is there any way to make this more efficient/reduce the amount of loops?有什么方法可以提高效率/减少循环数量?
【发布时间】:2019-05-23 14:39:38
【问题描述】:

给定一个 int n,使用 # 打印一个楼梯。这是来自黑客等级,楼梯问题。例子: n = 4。

输出:

   #
  ##
 ###
####

虽然每一行都有相同数量的列,但随着我们不断地遍历行,# 符号会增加,空间会减少。

我已经解决了问题,只是想看看有没有更有效的方法

public static void staircase(int n) {
    int spaceCounter = 0;

    for(int i = 1; i <= n; i++) { // Takes care of the rows
        spaceCounter = n - i;

        // Takes care of the column by printing a space until a # sign is required then it would print so.
        for (int j = 1; j <= spaceCounter; j++) {
            System.out.print(" ");

            if (j == spaceCounter) {
                //Prints as many #s as needed (n minus the number of spaces needed)
                for(int k = 1; k <= (n - spaceCounter); k++) {
                    System.out.print("#");
                }

               //makes sure it goes to the next life after being done with each row
                System.out.println();
            }
        }

        if (i == n) {
            for(int j = 1; j <= n; j++) {
                System.out.print("#");
            }
        }
    }
}

【问题讨论】:

  • 这更适合codereview.stackexchange.com。我们将在这里修复损坏的代码。
  • 由于您的代码目前有效,我相信它属于CodeReview(链接指向他们的如何提问)。
  • 对不起,这里有点新,但谢谢你,现在我知道了!

标签: java


【解决方案1】:

使用 Java 11,您可以利用 String#repeat 获得使用单个 for 循环的高效解决方案:

public static void staircase(int n) {
    for (int i = 1; i <= n; i++) {
        System.out.println(" ".repeat(n - i) + "#".repeat(i));
    }
}

我们所做的只是计算特定所需的空格数,然后所需的#字符数就是n减去使用的空格数。


如果n 是一个很大的值,您可以构建一个String(使用StringBuilder)然后打印它而不是调用System.out.println n 次:

public static void staircase(int n) {
    var sb = new StringBuilder();

    for (int i = 1; i <= n; i++) {
        sb.append(" ".repeat(n - i)).append("#".repeat(i)).append('\n');
    }

    System.out.print(sb);
}

【讨论】:

  • 你可以用print代替println来代替deleteCharAt。如果您假设println 会刷新缓冲区(通常会这样做),请显式调用flush
  • 谢谢! repeat 和 string builder 对我来说仍然是新的,但我可以理解它们是如何工作的。
  • 另外,如果我们谈论的是一个真正高效的解决方案,拥有两个StringBuilders不是更好吗?一个填充了在每次迭代中变短的空格,另一个填充了在每次迭代中变长的#,这样我们就不必经常调用repeat
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 2015-10-08
  • 2021-04-05
相关资源
最近更新 更多