leetcode 日经贴,Cpp code -Trapping Rain Water

来源:互联网 发布:尚硅谷周阳视频linux 编辑:程序博客网 时间:2024/05/16 12:13

Trapping Rain Water

class Solution {public:    int trap(vector<int>& height) {        int n = height.size();        stack<pair<int, int> >st;        int maxh = 0, omit = 0;        for (int i = 0; i < n; ++i) {            while (!st.empty() && st.top().second < maxh && st.top().second < height[i]) {                omit += st.top().second;                st.pop();            }            st.push(make_pair(i, height[i]));            maxh = max(maxh, height[i]);        }        int water = 0;        if (!st.empty()) {            pair<int, int> last = st.top();            st.pop();            while (!st.empty()) {                water += min(st.top().second, last.second) * (last.first - st.top().first - 1);                last = st.top();                st.pop();            }        }        return water - omit;    }};


class Solution {public:    int trap(vector<int>& height) {        int n = height.size();        stack<pair<int, int> >st;        int maxh = 0, omit = 0;        for (int i = 0; i < n; ++i) {            while (!st.empty()) {                int h = st.top().second;                if(h < maxh && h < height[i]) {                    omit += h;                    st.pop();                } else {                    break;                }            }            st.push(make_pair(i, height[i]));            maxh = max(maxh, height[i]);        }        int water = 0;        if (!st.empty()) {            pair<int, int> last = st.top();            st.pop();            while (!st.empty()) {                pair<int, int> cur = st.top();                water += min(cur.second, last.second) * (last.first - cur.first - 1);                last = cur;                st.pop();            }        }        return water - omit;    }};


0 0
原创粉丝点击