top1编程
← 返回题目
题解

【入门】沙漏

1 条题解

  • 0
    @ 2026-7-30 0:43:50

    解题思路

    按照题目要求直接计算。代码中使用简单的循环、判断和数组,把每一步写出来,方便理解。

    参考代码

    // 读取题目给出的数据。
    // 按照题意完成计算。
    // 输出最终答案。
    #include <iostream>
    using namespace std;
    int main() {
        int n;
        cin >> n;
        int mid = n / 2;
        for (int i = 0; i < n; i++) {
            int space = i <= mid ? i : n - 1 - i;
            int star = n - 2 * space;
            for (int j = 0; j < space; j++) cout << ' ';
            for (int j = 0; j < star; j++) cout << '*';
            cout << endl;
        }
        return 0;
    }
    

    复杂度

    代码只使用了题目需要的循环、判断和数组。若有 n 次循环,时间复杂度为 O(n);只使用固定数量变量时,空间复杂度为 O(1)。

    • 1