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.
這道題就是一個在第一象線有多個豎線,豎線長度就是高。兩條豎線之間距離就是底。求最大面積。不過由於水桶原理,最大面積是由最短的豎線決定的。同時,我們還要考慮底。因為S=底*高。
方法是從兩邊開始查詢,我們儘量要找兩條豎線都很高,並且豎線之間距離很遠的組合。所以對於中間低的豎線並且近的豎線可以不計算。每次計算完,更新max就可以了。
我寫的原始版本:
class Solution {
public:
int maxArea(vector<int>& height) {
const int size = height.size();
if(size < 2)
return 0;
int l = 0, r = size - 1;
int res = 0;
for(int i=0, j=size-1; i<j; ) {
if(height[i] > height[l])
l = i;
if(height[j] > height[r])
r = j;
res = std::max(res, std::min(height[i], height[j]) * (r-l));
if(height[i] < height[j])
++i;
else
--j;
}
return res;
}
};
精簡版本:
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1;
int res = 0;
while(i < j) {
int h = std::min(height[i], height[j]);
res = std::max(res, h * (j - i));
while(height[i] <= h && i < j) ++i;
while(height[j] <= h && i < j) --j;
}
return res;
}
};
相關文章
- LeetCode 11. Container With Most WaterLeetCodeAI
- LeetCode - Medium - 11. Container With Most WaterLeetCodeAI
- leetcode Container With Most WaterLeetCodeAI
- Leetcode 11 Container With Most WaterLeetCodeAI
- Leetcode-Container With Most WaterLeetCodeAI
- Container With Most Water leetcode javaAILeetCodeJava
- leetcode_11. Container With Most WaterLeetCodeAI
- [LeetCode] Container With Most Water 裝最多水的容器LeetCodeAI
- LeetCode Container With Most Water(011)解法總結LeetCodeAI
- [Most.js] Create Streams From Single Values With Most.jsJS
- Front Most Alfred WorkflowAlfred
- The most influential person
- Trapping Rain WaterAPPAI
- C. Mixing Water
- Traceback (most recent call last):AST
- H. The Most Reckless Defense
- Trapping-rain-waterAPPAI
- Ext.js4.2.1 Ext.container.ContainerJSAI
- 11. webpack配置VueWebVue
- 11.《開工天物》
- Container on AWSAI
- Afterall most women on quite a few skillUI
- LeetCode-Water and Jug ProblemLeetCode
- 水紋效果(Water)源程式. (轉)
- 11.死鎖(deadlocks)
- 11. 串列埠通訊串列埠
- 11. 名稱空間
- 11.物件導向(3)物件
- Container & MicroserviceAIROS
- container_of 分析AI
- docker之containerDockerAI
- Although it does not provide the most Parajumpers On SaleIDE
- 11.盛最多水的容器
- You are beautiful voted the 'Most Irritating Song Ever'.
- 2.3.7 Container MapsAI
- flutter Container的decorationFlutterAI
- Cloud Container Service experimentationCloudAI
- [LeetCode] 417. Pacific Atlantic Water FlowLeetCode