11. Container With Most Water 裝水最多的容器
[抄題]:
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.
[暴力解法]:
時間分析:
空間分析:
[思維問題]:
距離更近時,只有木板更高才能往前走,因此避免掃描多余狀態。頭一次總結到 對撞型兩根指針的思考方向是這樣,下次註意。
[一句話思路]:
用max反復比較,直到求出最大值
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
[復雜度]:Time complexity: O(n) Space complexity: O(n)
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
灌水問題就用 對撞型兩根指針
[關鍵模板化代碼]:
while (left < right)
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
public class Solution { /** * @param heights: a vector of integers * @return: an integer */ public int maxArea(int[] height) { //corner case intView Codemax = 0; int left = 0; int right = height.length - 1; while (left < right) { max = Math.max(max, Math.min(height[left], height[right]) * (right - left)); if (height[right] > height[left]) { left++; }else { right--; } } return max; } }
11. Container With Most Water 裝水最多的容器