[LeetCode] 11. Container With Most Water 裝最多水的容器
阿新 • • 發佈:2018-03-03
OS python oge containe 較高的 contains tco water IT
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.
與42. Trapping Rain Water 類似,兩條垂直的線和X軸組成一個容器,灌水多少不僅與兩個柱子的高度有關,也與兩個柱子的距離有關,公式:S(i,j) = min(ai, aj) * (j-i),容器不能傾斜,求容納最多水的兩個線組合。
用暴力搜索Brute Force, Time: O(n2)會超時。
使用雙指針two pointers。 定義left,right兩個指針,兩指針相遇循環結束。何時移動左右指針呢,保留較高的柱子,移動較矮的柱子。
Time complexity: O(n), Space complexity: O(1)
Java:
class Solution { public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int ans = 0; while (l < r) { int h = Math.min(height[l], height[r]); ans = Math.max(ans, h * (r - l)); if (height[l] < height[r]) ++l; else --r; } return ans; } }
Python:
class Solution: def maxArea(self, height): max_area, i, j = 0, 0, len(height) - 1 while i < j: max_area = max(max_area, min(height[i], height[j]) * (j - i)) if height[i] < height[j]: i += 1 else: j -= 1 return max_area
C++:
class Solution { public: int maxArea(const vector<int>& height) { int ans = 0; int l = 0; int r = height.size() - 1; while (l < r) { int h = min(height[l], height[r]); ans = max(ans, h * (r - l)); if (height[l] < height[r]) ++l; else --r; } return ans; } };
類似題目:
[LeetCode] 42. Trapping Rain Water 收集雨水
[LeetCode] 11. Container With Most Water 裝最多水的容器