微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检查是否存在索引 k 使得数组 A[] 的元素顺时针移动形成反向双调数组

如何解决检查是否存在索引 k 使得数组 A[] 的元素顺时针移动形成反向双调数组

检查是否存在索引0 <= k < n - 2,使得数组A[]的元素顺时针移动k索引组成一个反向双调数组。 我在 O(n) 时间复杂度内实现的方法

bool is_antibitonicable(int A[],int n) {
    // returns if there is such index k that 
    // after moving clockwise k elements of array
    // A[],that array is reverse bitonic
    // - strictly decreasing then strictly
    // increasing
    if (n < 3)
        return false;
    // if is_increasing[i] == 1 means this part of A[] is increasing,// == 0 means that part of A[] is decreasing,== -1 default
    int is_increasing[3] = { -1,-1,-1 };
    for (int i = 0,j; i < n - 1;) {
        if (A[i] < A[i + 1]) { // if A[] is increasing
            j = 0;
            while (j < 3 && is_increasing[j] != -1)
                j++;
            if (j == 3)
                return false;
            is_increasing[j] = 1;
            while (i < n - 1 && A[i] < A[i + 1])
                i++;
        }
        else if (A[i] > A[i + 1]) { // check if decreasing
            j = 0;
            while (j < 3 && is_increasing[j] != -1)
                j++;
            if (j == 3)
                return false;
            is_increasing[j] = 0;
            while (i < n - 1 && A[i] > A[i + 1])
                i++;
        }
        else // sequence of A[] is neither increasing nor decreasing
            return false;
    }
    // if A[] is only increasing/decreasing
    if (is_increasing[1] == is_increasing[2])
        return false;
    // if A[] is increasing->decreasing->increasing check if increasing
    // parts can be merged into one increasing sequence
    if (is_increasing[0] == 1 && is_increasing[1] == 0 && is_increasing[2] == 1)
        return (A[0] > A[n - 1]);
    // decreasing->increasing->decreasing
    if (is_increasing[0] == 0 && is_increasing[1] == 1 && is_increasing[2] == 0)
        return (A[0] < A[n - 1]);
    return true; // increasing -> decreasing or opposite
}

如果有人可以查看我的解决方案并评论它是否正确或如何做得更好,我将非常高兴,我们将不胜感激。

解决方法

您的解决方案看起来不错,但它不正确地return false // if A[] is only increasing/decreasing。这样的序列总是可以通过在(适当)方向旋转一个来变成先减少然后增加一个。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。