zoukankan      html  css  js  c++  java
  • LeetCode(11)题解: Container With Most Water

    https://leetcode.com/problems/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.

    思路:

    考虑从边界向里缩减范围。最重要的是注意到,假设现在边界的height是a和b,那么想在内部有别的点能比a、b框成的体积大,那么这个点一定得比a、b中的最小者大。所以不断从边界height较小的点向内缩减,直到内部为空。

    只需遍历数组一次,所以复杂度为O(n)。

    AC代码:

     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         int i,j,n=height.size(),a=0,b=n-1,contain=min(height[0],height[n-1])*(n-1);
     5         while(a<b){
     6             if(height[a]<height[b]){
     7                 for(i=a;i<b;i++){
     8                     if(height[i]>height[a])
     9                         break;
    10                 }
    11                 if(min(height[i],height[b])*(b-i)>contain){
    12                     contain=min(height[i],height[b])*(b-i);
    13                 }
    14                 a=i;
    15             }
    16             else{
    17                 for(j=b;j>a;j--){
    18                     if(height[j]>height[b])
    19                         break;
    20                 }
    21                 if(min(height[j],height[a])*(j-a)>contain){
    22                     contain=min(height[j],height[a])*(j-a);
    23                     }
    24                 b=j;
    25             }
    26         }
    27         return contain;
    28     }
    29 };
  • 相关阅读:
    使用PrintDocument进行打印
    【转】封装原生JS实现Ajax
    休眠到指定时分秒
    [原创]vscode初体验
    反编译网站
    命令行工具aspnet_regiis.exe实现加密和解密web.config
    Sqlserver内置函数实现MD5
    [转]如何循序渐进向dotnet架构师发展
    [转]高级系统架构师培训笔记
    理解RESTful
  • 原文地址:https://www.cnblogs.com/aezero/p/4706192.html
Copyright © 2011-2022 走看看