0
点赞
收藏
分享

微信扫一扫

算法问题——柱形图的面试盛水问题


容器盛水问题:​​https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f?tpId=117&&tqId=35269&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking​​

 

​​11. 盛最多水的容器​​

class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1;
int ans = 0;
while (l < r) {
int area = Math.min(height[l], height[r]) * (r - l);
ans = Math.max(ans, area);
if (height[l] <= height[r]) {
++l;
} else {
--r;
}
}
return ans;
}
}

​​84. 柱状图中最大的矩形​​

class Solution {
public int largestRectangleArea(int[] heights) {
int len = heights.length;
if (len == 0) {
return 0;
}
if (len == 1) {
return heights[0];
}
int Area = 0;
int[] newHeights = new int[len + 2];
for (int i = 0; i < len; i++) {
newHeights[i + 1] = heights[i];
}
len += 2;
heights = newHeights;
//栈中存放的是一个宽度的位置 当前位置的最高下标值
Deque<Integer> stack = new ArrayDeque<>();
stack.add(0);
for (int i = 1; i < len; i++) {
//当栈顶的元素大于当前的元素
while (heights[stack.peekLast()] > heights[i]) {
//栈顶的高度
int height = heights[stack.removeLast()];
//弹出栈
int width = i - stack.peekLast() - 1;
Area = Math.max(Area, width * height);
}
stack.add(i);
}
return Area;
}
}

 

举报

相关推荐

0 条评论