zoukankan      html  css  js  c++  java
  • LeetCode

    Container With Most Water

    2014.2.8 21:37

    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.

    Solution:

      A very plain solution is to do a O(n^2) scan, check out every pair of (a[i], a[j]) and find out the maximal min(a[i], a[j]) * (i - j).

      You know this is far from satisfactory, so let's try to find an O(n) solution.

      Suppose we've got a candidate pair (a[x], a[y]), the result is min(a[x], a[y]) * (x - y). If it is currently the optimal candidate, there cannot be any a[k] >= a[x] left of a[x], or any a[k] >= a[y] right of a[y], think about why.

      If we are to find a better solution (a[x'], a[y']), it must lie within the interval (x, y), and satify the condition (a[x'] > a[x] && a[y'] >= a[y]) or (a[x'] >= a[x] && a[y'] > a[y]).

      This means we can scan the array from both ends in one pass, and end the algorithm when both iteraotors meet in the middle.

      Time complexity is O(n), space complexity is O(1).

    Accepted code:

     1 // 1CE, 1AC, good.
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 class Solution {
     6 public:
     7     int maxArea(vector<int> &height) {
     8         if (height.empty()) {
     9             return 0;
    10         }
    11         
    12         int ll, rr, kk, result;
    13         
    14         ll = 0;
    15         rr = (int)height.size() - 1;
    16         result = 0;
    17         while (ll < rr) {
    18             result = max(result, min(height[ll], height[rr]) * (rr - ll));
    19             if (height[ll] < height[rr]) {
    20                 kk = ll + 1;
    21                 while (kk < rr && height[kk] <= height[ll]) {
    22                     ++kk;
    23                 }
    24                 ll = kk;
    25             } else {
    26                 kk = rr - 1;
    27                 while (kk > ll && height[kk] <= height[rr]) {
    28                     --kk;
    29                 }
    30                 rr = kk;
    31             }
    32         }
    33         
    34         return result;
    35     }
    36 };
  • 相关阅读:
    spring事务管理器设计思想(一)
    ThreaLocal内存泄露的问题
    denyhost防止SSH暴力破解
    qt下调用win32api 修改分辨率
    Windows下pip安装包报错:Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat
    Centos 6.5 下安装socket5代理
    Mac 下安装mitmproxy
    Mac OS 下安装wget
    判断客户端是否使用代理服务器及其匿名级别
    Mac OS 下安装rar unrar命令
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3541097.html
Copyright © 2011-2022 走看看