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;
        }
    };
  • 相关阅读:
    jquery Table基础操作
    window.opener
    CSS基础
    CSS样式
    CSS框架
    常用正则表达式
    HTML字体对应word字体
    SQL获取所有数据库名、表名、储存过程以及参数列表
    SQL集合运算:差集、交集、并集
    sql数据分页
  • 原文地址:https://www.cnblogs.com/grandyang/p/6115984.html
Copyright © 2011-2022 走看看