11. 盛最多水的容器

  • 2019 年 10 月 4 日
  • 筆記

題目描述

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.    Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.        Example:    Input: [1,8,6,2,5,4,8,3,7]  Output: 49

思路

符合直覺的解法是,我們可以對兩兩進行求解,計算可以承載的水量。然後不斷更新最大值,最後返回最大值即可。這種解法,需要兩層循環,時間複雜度是O(n^2)

eg:

// 這個解法比較暴力,效率比較低      // 時間複雜度是O(n^2)      let max = 0;      for(let i = 0; i < height.length; i++) {          for(let j = i + 1; j < height.length; j++) {              const currentArea = Math.abs(i - j) * Math.min(height[i], height[j]);              if (currentArea > max) {                  max = currentArea;              }          }      }      return max;

這種符合直覺的解法有點像冒泡排序, 大家可以稍微類比一下

那麼有沒有更加優的解法呢?我們來換個角度來思考這個問題,上述的解法是通過兩兩組合,這無疑是完備的, 那我門是否可以先計算長度為n的面積,然後計算長度為n-1的面積,… 計算長度為1的面積。這樣去不斷更新最大值呢?很顯然這種解法也是完備的,但是似乎時間複雜度還是O(n ^ 2), 不要着急。

考慮一下,如果我們計算n-1長度的面積的時候,是直接直接排除一半的結果的。

如圖:

比如我們計算n面積的時候,假如左側的線段高度比右側的高度低,那麼我們通過左移右指針來將長度縮短為n-1的做法是沒有意義的, 因為 新的形成的面積變成了(n-1)*heightOfLeft這個面積一定比剛才的長度為n的面積nn*heightOfLeft小

也就是說最大面積 一定是當前的面積或者通過移動短的線段得到

關鍵點解析

  • 雙指針優化時間複雜度

代碼

  • 語言支持:JS,C++

JavaScript Code:

/*   * @lc app=leetcode id=11 lang=javascript   *   * [11] Container With Most Water   *   * https://leetcode.com/problems/container-with-most-water/description/   *   * algorithms   * Medium (42.86%)   * Total Accepted:    344.3K   * Total Submissions: 790.1K   * Testcase Example:  '[1,8,6,2,5,4,8,3,7]'   *   * 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.   *   * Note: You may not slant the container and n is at least 2.   *   *   *   *   *   * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In   * this case, the max area of water (blue section) the container can contain is   * 49.   *   *   *   * Example:   *   *   * Input: [1,8,6,2,5,4,8,3,7]   * Output: 49   *   */  /**   * @param {number[]} height   * @return {number}   */  var maxArea = function(height) {      if (!height || height.length <= 1) return 0;        // 雙指針來進行優化      // 時間複雜度是O(n)      let leftPos = 0;      let rightPos = height.length - 1;      let max = 0;      while(leftPos < rightPos) {            const currentArea = Math.abs(leftPos - rightPos) * Math.min(height[leftPos] , height[rightPos]);          if (currentArea > max) {              max = currentArea;          }          // 更新小的          if (height[leftPos] < height[rightPos]) {              leftPos++;          } else { // 如果相等就隨便了              rightPos--;          }      }        return max;  };

C++ Code:

class Solution {  public:      int maxArea(vector<int>& height) {          auto ret = 0ul, leftPos = 0ul, rightPos = height.size() - 1;          while( leftPos < rightPos)          {              ret = std::max(ret, std::min(height[leftPos], height[rightPos]) * (rightPos - leftPos));              if (height[leftPos] < height[rightPos]) ++leftPos;              else --rightPos;          }          return ret;      }  };