题解 | #有序序列判断#

又是一个不用数组系列 用到一个非常基本的数学 (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 江西

相关推荐

05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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