`
ouqi
  • 浏览: 42147 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Container With Most Water 和Largest Rectangle in Histogram

 
阅读更多

这两题看起来有点像,但是实际上是完全不一样的,区别在于:

The "Container With Most Water" solution will allow the water to rise above intermediate positions. With the "largest rectangle" problem, the rectangle cannot rise above intermediate bars.
也就是说Container With Most Water只考虑左右边界,[i,j]范围内的Area = min(height[i],height[j]) * (j-i);Largest Rectangle in Histogram,高度最小值为[i,j]范围内所有高度的最小值。后者比前者要难很多
1.Container With Most Water
对于这题,考虑左右边界[i,j] ,当height[i]<height[j]时,因为i是其中的短板,则无论j取[i+1,j]中的任何值,Area都只会比当前已求出的[i,j]的Area小(横坐标范围减小,再遇见比height[i]更小的右边界),因此以i为左边界的情况不再考虑,i++;反之,j--,同样的思考方式。
代码:
public class Solution {
    public int min(int i,int j){
        return i<j?i:j;
    }
    public int maxArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(height == null) return 0;
        int i = 0;
        int j = height.length -1;
        int max = 0;
        
        while(i<j){
            int area = min(height[i],height[j])*(j-i);
            if(area>max) max = area;
            if(height[i]<height[j]) i++;
            else j--;
        }
        return max;
    }
}
 
Largest Rectangle in Histogram 
代码如下:
public int largestRectangleArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(height == null) return 0;
        int len = height.length;
        Stack<Integer> stack = new Stack<Integer>();
        Stack<Integer> width = new Stack<Integer>();//记录向左可以扩展的宽度
        int max = 0;
        stack.push(0);
        width.push(0);
        
        int h;
        for(int i = 0;i<=len;i++){ 
            if(i == len) h = 0;
            else h = height[i];
            int wid = 0;
            while(h<stack.peek()){
                //1.算自己的左边界
                //2.已放入栈中的高度>h的右边界已经找到了
                int top = stack.pop();
                wid += width.pop();
                max = Math.max(max,top*wid);
                }
            stack.push(h);
            width.push(Math.max(wid+1,1));//每次加入stack的时候,他的左边界就已经确定了
           
        }
        return max;
    }
 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics