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

    Analyse: Set two variables, left and right to represent the leftmost and rightmost element respectively. We increase left and decrease right gradually. If the moving items are smaller than height[left] and height[right], then we don't need to change the value of left and right. Otherwise, we change the values and compare the area with the former computed one. 

    Runtime: 32ms.

     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         if(height.empty()) return 0;
     5         
     6         int left = 0, right = height.size() - 1;
     7         int result = 0;
     8         while(left <= right){
     9             int h = min(height[left], height[right]);
    10             result = max(result, h * (right - left));
    11             
    12             if(height[left] > height[right]){
    13                 int index = right;
    14                 while(left <= index && height[index] <= height[right])
    15                     index--;
    16                 right = index;
    17             }
    18             else{
    19                 int index = left;
    20                 while(index <= right && height[index] <= height[left])
    21                     index++;
    22                 left = index;
    23             }
    24         }
    25         return result;
    26     }
    27 };
  • 相关阅读:
    CAD输出图至Word
    win7激活工具
    IP地址出现错误
    x%内存可用的问题解决
    第一次来到博客园
    ++x和x++
    标准输入流输出流以及错误流
    关于main函数的参数
    hdu1465 动态规划
    静态变量(static)的特点
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4777511.html
Copyright © 2011-2022 走看看