classSolution{publicint[]nextGreaterElements(int[] nums){if(nums ==null|| nums.length <=1)returnnewint[]{-1};int len = nums.length;int[] res =newint[len];Arrays.fill(res,-1);Stack<Integer> st =newStack<>();for(int i =0; i < len *2; i++){while(!st.isEmpty()&& nums[i % len]> nums[st.peek()]){
res[st.peek()]= nums[i % len];
st.pop();}
st.push(i % len);}return res;}}
42. 接雨水
学习文章链接:
思路:优先理解单调栈的解法。
代码:
classSolution{publicinttrap(int[] height){int len = height.length;if(len <=2)return0;Stack<Integer> st =newStack<>();
st.push(0);int sum =0;for(int i =1; i < len; i++){if(height[i]< height[st.peek()]){
st.push(i);}elseif(height[i]== height[st.peek()]){
st.pop();
st.push(i);}else{while(!st.isEmpty()&& height[i]> height[st.peek()]){int mid = st.pop();if(!st.isEmpty()){int left = st.peek();int h =Math.min(height[left], height[i])- height[mid];int w = i - left -1;if(h * w >0) sum += h * w;}}
st.push(i);}}return sum;}}