zoukankan      html  css  js  c++  java
  • [LeetCode]99. 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.

    Subscribe to see which companies asked this question

    在第一象限存在点(1,a1),(2,a2),...,(n,an),这些点各自与(1,0),(2,0),...,(n,0)连成一条条垂直线,任取两条(i,ai)和(j,aj),与(i,j)组成一个容器,求能够得到的最大容积的(i,ai)和(j,aj)。

    解法1:暴力破解,两层循环求出所有容器的容积,然后取最大值。Time Limit Exceeded

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int n = height.size(), maxContain = 0;
            for (int i = 0; i < n - 1; ++i) {
                for (int j = i + 1; j < n; ++j) {
                    int minHeight = min(height[i], height[j]);
                    int contain = (j - i) * minHeight;
                    if (contain > maxContain) maxContain = contain;
                }
            }
            return maxContain;
        }
    };

    解法2:题目提示使用两个指针。两个指针指向数组两端,计算出容积并更新结果;然后比较左右直线的高度,将高度较小的那个移动一步;直到两个指针相遇。

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int left = 0, right = height.size() - 1, maxContain = 0;
            while (left < right) {
                maxContain = max(min(height[left], height[right]) * (right - left), maxContain);
                if (height[left] < height[right]) ++left;
                else --right;
            }
            return maxContain;
        }
    };
  • 相关阅读:
    [POI2013]BAJ-ytecomputer [动态规划]
    【2019.10.15】网课 Za
    【初赛】
    [NOI2014]魔法森林[最短路 spfa]
    【洛谷2019金秋营模拟赛1】
    【luogu1315】 观光公交[贪心]
    【luogu4450】收集邮票 [期望dp]
    [HAOI2012]高速公路 [线段树 期望]
    ALGO-185 Trash Removal
    精度计算——减法
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5021268.html
Copyright © 2011-2022 走看看