[LeetCode] 11. Container With Most Water My Submissions Question 解题思路

时间:2023-03-08 18:20:52
[LeetCode] 11. Container With Most Water My Submissions Question 解题思路

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

问题:给定 n 个元素的数组 a1,a2..an,他们对应坐标中的 n 条线,第 i 条线的两端分别为坐标 (i, 0) 和 (i, ai)。求两根线,这两个线和 x 轴形成的容器能装最多的水。

这是一道直方图相关的题目,同样是直方图的题目还有:Trapping Rain Water 和 Largest Rectangle in Histogram。他们的解法有类似的地方,就是借助于递增元素以及对应的下标来计算。

  • 分别找出从左往右递增元素 Ls ,以及从右往左的递增元素 Rs 。
  • 用 Ls 的元素分别依次和 Rs 的元素组合形成容器,在所有结果中找到最大值就是原题目的解。

优化点:第二部做乘法时候,当 Ls[i] < Rs[k] 时候,Ls[i] 和 其他大于 Rs[k] 的组合可以不用再算,必然小于 Ls[i] 和 Rs[k] 。

     int maxArea(vector<int>& height) {

         if (height.size() < ){
return ;
} vector<int> idxAsceL; idxAsceL.push_back(); for (int i = ; i < height.size(); i++) { if (height[i] > height[idxAsceL.back()]) {
idxAsceL.push_back(i);
}
} vector<int> idxAsceR;
idxAsceR.push_back((int)height.size()-); for (int i = (int)height.size() - ; i >= idxAsceL.back(); i--) {
if (height[i] > height[idxAsceR.back()]) {
idxAsceR.push_back(i);
}
} int maxA = ;
for (int i = ; i < idxAsceL.size(); i++) {
for (int k = ; k < idxAsceR.size(); k++) { int l = idxAsceL[i];
int r = idxAsceR[k]; int h = min(height[l], height[r]); int len = r - l;
maxA = max(maxA, h * len); if (height[l] <= height[r]) {
break;
}
}
} return maxA;
}