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;
    }
};
全部评论

相关推荐

神哥不得了:神哥来啦~1.建议不要包装,很容易问穿2.没日常也能找到暑期3.简历模板换一下,字体和版式看着好难受,而且最好压缩到一页,技术的倒数第2和3重复啦,项目建议换两个高质量的上去,如果时间够的话,八股就把高频top50的题目多巩固几遍,吃透,注意不要找假高频,这样绝对能找到暑期
点赞 评论 收藏
分享
03-10 20:35
已编辑
武汉大学 C++
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务