*[codility]StoneWall

https://codility.com/demo/take-sample-test/stone_wall

拼石块。用最少的方块。一开始想了想用贪心,是可行的,就是尽量每次把当前的高度往右延伸到最多,比如7,8,7,那么7往右延伸可以覆盖到第二个7,这样减掉,后面的就变成1,0了,问题仍然等价。
但这样要O(n^2)。结果需要O(n)的复杂度。这个时候就想到了单调栈。
于是栈中只记录递增的序列,发现比top当前的大就pop,因为这个对之后的已经没有作用了。因为每个元素都进栈出栈一次,平摊下来是O(n)的。
第一次自己想出单调栈的解法,开心。

// you can also use includes, for example:
// #include <algorithm>
#include <stack>
int solution(const vector<int> &H) {
    // write your code in C++98
    stack<int> st;
    int count = 0;
    for (int i = 0; i < H.size(); i++) {
        while (!st.empty() && st.top() > H[i]) {
            st.pop();
        }
        if (!st.empty() && st.top() == H[i]) {
            continue;
        }
        else { // st.top < H[i] || st.empty()
            count++;
            st.push(H[i]);
        }
    }
    return count;
}

  

 

posted @ 2013-11-14 21:26  阿牧遥  阅读(682)  评论(0编辑  收藏  举报