版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/81870515
其实这就是LeetCode上的一道题目,再次证明了LeetCode在面试中的巨大作用。
原题参考:84. Largest Rectangle in Histogram
经过不懈努力,终于在抄抄抄的过程中把题目解出来了。
import java.util.Stack;
class Solution {
private int max = 0;
private Stack<Integer> stack = new Stack<>();
public int largestRectangleArea(int[] heights) {
int n = heights.length;
if (heights == null || n == 0) {
return 0;
}
for(int i = 0; i<n;i++){
if (stack.isEmpty()) {
stack.push(i);
continue;
}
if(heights[i]>heights[stack.peek()]){
stack.push(i);
continue;
}
while(!stack.isEmpty() && heights[i]<heights[stack.peek()]){
updateMax(heights,i);
}
stack.push(i);
}
while (!stack.isEmpty()) {
updateMax(heights, heights.length);
}
return max;
}
private void updateMax(int[] heights, int right) {
int curIndex = stack.pop();
int h = heights[curIndex];
// 计算边界
// 如果栈的元素大于1,那么左边界是前一个元素下标+1
// 如果栈的元素等于1,那么左边界就是0
int left = stack.isEmpty()?0:stack.peek()+1;
int w = right - left;
int area = w * h;
if(max<area){
max = area;
}
}
}
测试代码
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class SolutionTest {
private Solution solution;
@Before
public void setUp() throws Exception {
solution = new Solution();
}
@Test
public void test_1() {
int max = solution.largestRectangleArea(new int[]{2,1,5,6,2,3});
Assert.assertEquals(10,max);
}
@Test
public void test_2() {
int max = solution.largestRectangleArea(new int[]{2,1});
Assert.assertEquals(2,max);
}
@Test
public void test_3() {
int max = solution.largestRectangleArea(new int[]{1,2});
Assert.assertEquals(2,max);
}
@Test
public void test_4() {
int max = solution.largestRectangleArea(new int[]{1,2,1});
Assert.assertEquals(3,max);
}
@Test
public void test_5() {
int max = solution.largestRectangleArea(new int[]{2,1,2});
Assert.assertEquals(3,max);
}
@Test
public void test_6() {
int max = solution.largestRectangleArea(new int[]{1,3,2,3});
Assert.assertEquals(6,max);
}
@Test
public void test_7() {
int max = solution.largestRectangleArea(new int[]{5,4,1,2});
Assert.assertEquals(8,max);
}
}
感情下次写算法的时候,能少写一个{
绝不多写一个}
,哈哈哈