c++下推栈 | #接雨水问题#

接雨水问题

http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

因为要获取栈底元素大小,STL没有相关函数,则自定义了一个栈,增加getFirst函数。

private:
    int size;
    int* s;
    int index;
public:
    void init(int n) {
        size = n;
        s = new int[n + 1];
        index = 0;
    }
    
    void push(int item) {
        s[index++] = item;
    }
    
    void pop() {
        if (index > 0) {
            index--;
        }
    }
    
    int top() {
        return s[index - 1];
    }
    
    bool empty() {
        return index == 0;
    }
    
    int getFirst() {
        return s[0];
    }
};

class Solution {
public:
    /**
     * max water
     * @param arr int整型vector the array
     * @return long长整型
     */
    long long maxWater(vector<int>& arr) {
        MyStack s;
        s.init(arr.size());
        long long ans = 0;
        for (int item: arr) {
            if (s.empty() == true) {
                s.push(item);
                continue;
            }
            
            if (item <= s.top()) {
                s.push(item);
            } else {
                int count = 0;
                int hight = min(item, s.getFirst());
                while (!s.empty() && s.top() < item) {
                    ans += (hight - s.top());
                    s.pop();
                    count++;
                }
                
                if (s.empty() == true) {
                    s.push(item);
                } else {
                    while (count-- >= 0) {
                        s.push(item);
                    }
                }
            }
        }
        
        return ans;
    }
};
全部评论

相关推荐

06-26 15:35
武汉大学 运营
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-30 18:19
个个985的硕士闭着眼睛都有15k以上的月薪,天天嚷嚷着研究生白度读了,天天嚷嚷着反向读研了........
MMMJC:不读研22本科出去的基本都拿28k呢,你不能用25的研究生和25的本科生比然后说没反向读研,而是25研和22本比呀
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务