day59|503.下一个更大元素II ● 42. 接雨水

503.下一个更大元素II

i%nums.size() 好啊
class Solution {
public:
    vector nextGreaterElements(vector& nums) {
        
        vector res(nums.size(),-1);
        if(nums.size()==0) return res;

        stack st;
        st.push(0);
        for(int i=1;i nums[st.top()]){
                    res[st.top()] = nums[i%nums.size()];
                    st.pop();
                }
                st.push(i%nums.size());
            }

        }
        return res;

    }
};

42. 接雨水

class Solution {
public:
    int trap(vector& height) {
        if(height.size()==2) return 0;
        stack st;
        st.push(0);
        int sum=0;
        for(int i=1;iheight[st.top()]){
                    int mid =st.top();
                    st.pop();
                    if(!st.empty()){
                        int h = min(height[i],height[st.top()]) - height[mid];
                        int  w = i-st.top()-1;
                        sum += h*w;
                    }
                }
                st.push(i);   
            }
        }
        return sum;
    }
};

你可能感兴趣的:(leetcode,算法,c++)