且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

O(nlgn)中最长的非递减子序列

更新时间:2023-01-10 09:40:39

除了 binary_search()函数中的问题,此函数应返回大于目标元素(x)的第一个元素的索引,因为您需要最长的非递减序列。对此进行修改,就可以了。

Your code nearly works except a problem in your binary_search() function, this function should return the index of the first element that's greater than the target element(x) since you want the longest non-decreasing sequence. Modify it to this, it'll be OK.

如果使用c ++,则 std :: lower_bound() std :: upper_bound ()将帮助您摆脱这个令人困惑的问题。顺便说一下,if语句 if(height [s [k]]> = height [i])是多余的。

If you use c++, std::lower_bound() and std::upper_bound() will help you get rid of this confusing problem. By the way, the if statement"if (height[s[k]] >= height[i])" is superfluous.

int binary_search(int first, int last, int x) {

    while(last > first)
    {
        int mid = first + (last - first) / 2;
        if(height[s[mid]] > x)
            last = mid;
        else
            first = mid + 1;
    }

    return first; /* or last */
}