• 11. Container With Most Water


    Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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 and n is at least 2.

    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

    Example:

    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49

    two pointers

    p1, p2分别从首、尾开始扫描数组,同时计算面积。长方形面积中的底是一直在减小的(每次减少1),高是两条边中较短的边长,如果当前p1对应的边长小于p2对应的边长,应该保留较长的边(即p2),p2不变,p1向右移动,面积增大的可能性更大(理由:如果保留p1而移动p2,如果p2移动后变大,边长还是取较短的p1,如果p2移动后变小,边长取这个较小的新边长。新的边长 <= p1,即,移动后边长不会增加;但是如果保留p2而移动p1的话,如果p1移动后变大,边长可以取新的较大的边长或p2,即,移动后边长有增加的可能)。反之则应该移动p2。

    时间:O(N),空间:O(1)

    class Solution {
        public int maxArea(int[] height) {
            int p1 = 0, p2 = height.length - 1;
            int max = 0;
            while(p1 < p2) {
                int area = (p2 - p1) * Math.min(height[p1], height[p2]);
                max = Math.max(max, area);
                if(height[p1] < height[p2])
                    p1++;
                else
                    p2--;
            }
            return max;
        }
    }
  • 相关阅读:
    PgSQL定时备份
    如何从源码包安装软件?
    PostgreSQL PointInTime Recovery (Incremental Backup)
    Better PostgreSQL backups with WAL archiving
    安装GTK全攻略
    WEB前端开发规范文档
    Linux开机自动启动脚本方法
    安装编译postgresql与pgagent的相关操作
    PostgreSQL: 如何查询表的创建时间?
    什么是编程
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10061968.html
Copyright © 2020-2023  润新知