longest nondecreasing subsequence in O(nlgn)

前端 未结 5 1953
无人及你
无人及你 2021-01-06 04:07

I have the following algorithm which works well

I tried explaining it here for myself http://nemo.la/?p=943 and it is explained here http://www.geeksforgeeks.org/lon

5条回答
  •  佛祖请我去吃肉
    2021-01-06 04:38

    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.

    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 */
    }
    

提交回复
热议问题