publicinttrap(int[] height){int ans =0;int size = height.length;for(int i =1; i < size -1; i++){int max_left =0, max_right =0;for(int j = i; j >=0; j--){//Search the left part for max bar size
max_left = Math.max(max_left, height[j]);}for(int j = i; j < size; j++){//Search the right part for max bar size
max_right = Math.max(max_right, height[j]);}
ans += Math.min(max_left, max_right)- height[i];}return ans;}
作者:LeetCode
链接:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法 2:动态编程
publicinttrap(int[] height){if(height == null || height.length ==0)return0;int ans =0;int size = height.length;int[] left_max =newint[size];int[] right_max =newint[size];
left_max[0]= height[0];for(int i =1; i < size; i++){
left_max[i]= Math.max(height[i], left_max[i -1]);}
right_max[size -1]= height[size -1];for(int i = size -2; i >=0; i--){
right_max[i]= Math.max(height[i], right_max[i +1]);}for(int i =1; i < size -1; i++){
ans += Math.min(left_max[i], right_max[i])- height[i];}return ans;}
作者:LeetCode
链接:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法 3:栈的应用
publicinttrap(int[] height){int ans =0, current =0;
Deque<Integer> stack =newLinkedList<Integer>();while(current < height.length){while(!stack.isEmpty()&& height[current]> height[stack.peek()]){int top = stack.pop();if(stack.isEmpty())break;int distance = current - stack.peek()-1;int bounded_height = Math.min(height[current], height[stack.peek()])- height[top];
ans += distance * bounded_height;}
stack.push(current++);}return ans;}
作者:LeetCode
链接:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法 4:使用双指针
publicinttrap(int[] height){int left =0, right = height.length -1;int ans =0;int left_max =0, right_max =0;while(left < right){if(height[left]< height[right]){if(height[left]>= left_max){
left_max = height[left];}else{
ans +=(left_max - height[left]);}++left;}else{if(height[right]>= right_max){
right_max = height[right];}else{
ans +=(right_max - height[right]);}--right;}}return ans;}
作者:LeetCode
链接:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。