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

     Notice

    You may not slant the container.

    Example

    Given [1,3,2], the max area of the container is 2.

    LeetCode上的原题,请参见我之前的博客Container With Most Water

    解法一:

    class Solution {
    public:
        /**
         * @param heights: a vector of integers
         * @return: an integer
         */
        int maxArea(vector<int> &heights) {
            int res = 0, i = 0, j = heights.size() - 1;
            while (i < j) {
                res = max(res, min(heights[i], heights[j]) * (j - i));
                heights[i] < heights[j] ? ++i : --j;
            }
            return res;
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param heights: a vector of integers
         * @return: an integer
         */
        int maxArea(vector<int> &heights) {
            int res = 0, i = 0, j = heights.size() - 1;
            while (i < j) {
                int h = min(heights[i], heights[j]);
                res = max(res, h * (j - i));
                while (i < j && h == heights[i]) ++i;
                while (i < j && h == heights[j]) --j;
            }
            return res;
        }
    };
  • 相关阅读:
    物理-接触力:百科
    物理-二力平衡:百科
    物理-摩擦力:百科
    物理-电磁力/静电力:百科
    物理-重力:百科
    化学-分子间作用力:百科
    物理-分子力:百科
    物理-斥力:百科
    物理-粒子/能量-衰变:百科
    物理-超光速:百科
  • 原文地址:https://www.cnblogs.com/grandyang/p/6115984.html
Copyright © 2011-2022 走看看