zoukankan      html  css  js  c++  java
  • LeetCode 11. Container With Most Water 单调队列

    题意

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

    Note: You may not slant the container.

    思路

    假如有容器如下图:

    那么他装满水之后一定是这个样子:

    可以看出,其从中间到两边一定是呈阶梯状下降的,中间的空缺一定会被水填上的。所以我们只需要枚举上图中由蓝色组成的矩形即可。

    开始做的时候竟然不会做了。然后问了下学妹,说是单调队列,发现不会写…… 真是忧伤。

    代码

    public class Solution {
        public int maxArea(int[] height) {
            int l = 0;
            int r = height.length - 1;
            int rlt = calcArea(l, r, height);
            while (l < r) {
                if (height[l] < height[r]) {
                    l = nextLeftBoard(l, r, height);
                } else {
                    r = nextRightBoard(l, r, height);
                }
                rlt = Math.max(calcArea(l, r, height), rlt);
            }
            return rlt;
        }
        
        private int nextLeftBoard(int l, int r, int[] height) {
            int rlt = l;
            while (rlt < r && height[rlt] <= height[l])
                rlt ++;
            return rlt;
        }
        
        private int nextRightBoard(int l, int r, int[] height) {
            int rlt = r;
            while (l < rlt && height[rlt] <= height[r])
                rlt --;
            return rlt;
        }
        
        private int calcArea(int l, int r, int[] height) {
            int h = Math.min(height[l], height[r]);
            return (r-l) * h;
        }
    }
    
  • 相关阅读:
    利用反馈字段给帝国cms添加留言板功能(图文教程)
    对程序员的不尊重是中国it产业的悲哀。
    网站原创文章被盗用怎么办?
    Vector
    iptables
    spark geoip
    geoip scala api
    matlab解三元二次方程组
    统计一个目录下所有普通文本文件的总行数
    awk多模式匹配
  • 原文地址:https://www.cnblogs.com/Phantom01/p/5871977.html
Copyright © 2011-2022 走看看