题解 | #有序序列判断#

又是一个不用数组系列 用到一个非常基本的数学 (b-a)*(c-b)>=0,那么a,b,c就是有序的

#include <iostream>
using namespace std;
int main()
{
    int len;
    cin>>len;
    int a,b;
    cin>>a>>b;
    int c;
    len -= 2;
    bool active = false;
    while(len--)
    {
        cin>>c;
        if((b-a)*(c-b)>=0)
        {
            a = b;
            b = c;
            active = true;
        }
        else
        {
            cout<<"unsorted";
            active = false;
            break;
        }
    }
    if(active) cout<<"sorted";
    return 0;
}

我感觉我的代码还是有点繁琐,有没有人可以优化一下 谢谢,点个赞再走吧

几年后的优化:修改了一下代码的判断

#include <iostream>
using namespace std;

int main() {
    int len;
    cin >> len;
    
    if (len < 3) {
        cout << "sorted" << endl;
        return 0;
    }

    int a, b, c;
    cin >> a >> b;

    bool increasing = (b >= a);
    bool decreasing = (b <= a);

    for (int i = 2; i < len; ++i) {
        cin >> c;

        if ((increasing && c < b) || (decreasing && c > b)) {
            cout << "unsorted" << endl;
            return 0;
        }

        a = b;
        b = c;
    }

    cout << "sorted" << endl;
    return 0;
}
全部评论
int main() { int n, tmp1, tmp2 = 0, tmp3 = 0; scanf("%d\n%d %d", &n,&tmp1,&tmp2); for (int i = 0; i < n-2; i++) { scanf("%d", &tmp3); if ((tmp2 - tmp1)*(tmp3-tmp2)>=0) { tmp1 = tmp2; tmp2 = tmp3; continue; } printf("unsorted"); return 0; } printf("sorted"); return 0; }
点赞 回复 分享
发布于 2024-11-06 21:17 江西

相关推荐

仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
迟缓的斜杠青年巴比Q...:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务