1 条题解

  • 0
    @ 1992-8-24 23:40:40

    【深基4.例2】找最小值

    解题思路

    初始化最小值为 INT_MAX,每读入一个数便更新为两者较小值。

    正确性说明

    处理前 k 个数后维护值等于这 k 个数的最小值,加入新数时取 min 保持不变式,最终得到全部数的最小值。

    易错点

    不要初始化为 0,因为输入全部为正时会错误输出 0。

    复杂度

    时间 O(n),空间 O(1)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, ans = INT_MAX;
        cin >> n;
        while (n--) {
            int x;
            cin >> x;
            ans = min(ans, x);
        }
        cout << ans << "\n";
        return 0;
    }
    
    • 1