Leetcode-11-Container-With-Most-Water
題目
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1
1 | Input: height = [1,8,6,2,5,4,8,3,7] |
Example 2
1 | Input: height = [1,1] |
解釋題目
height 是一個 integer array,每一個元素代表一個線段的高度。
任意兩條線段,沿著 X 軸方向,可以假想成一個容器,容器不能傾斜。
求容器最大能容納的水量。
思路
- Initial: 左指針指向最前面的 height,右指針指向最後面的 height。
- 開始計算水量,記錄最大水量。
- 若左邊的高度較矮,左指針就右移。若右邊的高度較矮,右指針就左移。移完指針後,回到第二步。
- 透過 Two Pointers,就能把所有狀況跑一遍。
程式碼
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 記錄程式的地方!
評論