You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用while、if判断整数序列为升序/降序/非单调的实现方案

非单调序列判定实现方案

原有代码问题

  • 判定逻辑错误:错误使用ascending>2、descending>2作为非单调判定条件,不符合需求规则
  • 缺失边界情况处理:未覆盖有效高度不足2个、所有数值相等的场景
  • 输出逻辑冲突:多个条件判断独立运行,可能同时输出多个结果
  • 相邻相等场景处理偏差:未正确对应示例中允许相等元素计入升/降序的规则

正确实现代码

#include <iostream>
using namespace std;

int main() {
    int prev, curr;
    int up_cnt = 0, down_cnt = 0;
    int valid_num = 0;

    cin >> prev;
    if (prev != 0) {
        valid_num = 1;
    }

    while (prev != 0) {
        cin >> curr;
        if (curr == 0) {
            break;
        }
        valid_num++;
        if (prev < curr) {
            up_cnt++;
        } else if (prev > curr) {
            down_cnt++;
        }
        prev = curr;
    }

    if (valid_num < 2) {
        cout << "non-monotonous";
    } else if (down_cnt == 0 && up_cnt > 0) {
        cout << "ascending";
    } else if (up_cnt == 0 && down_cnt > 0) {
        cout << "descending";
    } else {
        cout << "non-monotonous";
    }
    return 0;
}

实现逻辑说明

  • 读取输入时自动跳过结束标记0,统计有效高度的数量
  • 遍历相邻元素对,分别统计上升、下降的对数,相等的相邻对不影响升/降序判定
  • 判定规则:
    1. 有效高度不足2个时直接判定为非单调
    2. 无下降对且存在上升对时判定为升序
    3. 无上升对且存在下降对时判定为降序
    4. 其余场景全部判定为非单调,覆盖所有元素相等、同时存在上升和下降对的情况

内容的提问来源于stack exchange,提问作者Large_Emu3782

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:04