題目html
給定 n 個非負整數 a1,a2,...,an,每一個數表明座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器能夠容納最多的水。git
說明:你不能傾斜容器,且 n 的值至少爲 2。github
圖中垂直線表明輸入數組 [1,8,6,2,5,4,8,3,7]。在此狀況下,容器可以容納水(表示爲藍色部分)的最大值爲 49。算法
輸入: [1,8,6,2,5,4,8,3,7] 輸出: 49
解題數組
public int MaxArea(int[] height) { if (height.Length <= 1) return 0; int max = 0; for (int i = 0; i < height.Length; i++) { for (int k = i + 1; k < height.Length; k++) { int area = System.Math.Min(height[i], height[k]) * (k - i); max = System.Math.Max(area, max); } } return max; }
這個算法真的很慢ide
設left = 0 , right = length - 1 計算容量spa
若left 比 right 矮(height[left] < height[right]) left++,反之 right--指針
咱們知道容量有2個因素引發,高度 * 寬度,左邊指針移動或右邊移動都會減小寬度code
只須要遍歷一次數組,時間複雜度:O(n)htm
public int MaxArea(int[] height) { int maxArea = 0; for (int left = 0, right = height.Length - 1; left < right;) { int area = System.Math.Min(height[left], height[right]) * (right - left); maxArea = System.Math.Max(area, maxArea); if (height[left] < height[right]) left++; else right--; } return maxArea; }
比算法一快了10倍
來源:力扣(LeetCode)連接:https://leetcode-cn.com/problems/reverse-integer