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 };
  • 相关阅读:
    作业day04
    python开发学习day03 (基本数据类型; 输入输出; 基本运算符)
    作业day03
    作业day02
    python开发学习day02 (编程语言; 解释器 ; 运行方式; IDE; 变量)
    BasePage基础页面的封装
    设定浏览器驱动
    webdriver(chrome无头浏览器)
    webdriervAPI(窗口截图)
    webdriervAPI(常用的js方法)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4777511.html
Copyright © 2011-2022 走看看