您的位置:首页 > 其它

柱状图内最大的矩形面积 Largest Rectangle in Histogram @LeetCode

2013-12-31 12:52 731 查看
1 暴力法,TLE
2 很巧妙的用了两个stack,一个stack保存高度,另一个保存index
遍历height数组,
1 如果stack为空或者当前元素的高度大于height stack顶元素(前一个元素)的高度 => 把当前高度额index分别添加到两个stack顶
2 如果当前元素的高度等于height stack顶元素的高度 => 什么都不做
3 如果当前元素的高度小于height stack顶元素的高度 => 持续弹栈直到当前元素的高度大于栈顶元素,并每次都计算面积(height * (current index - popped index)),保存最大面积。最后把当前高度和最后一个弹出的index(非当前index) 重新压入栈中
4 处理完height数组,如果stack非空,则一一弹栈并计算面积。
http://www.youtube.com/watch?v=E5C5W6waHlo

package Level5;

import java.util.Stack;

/**
* Largest Rectangle in Histogram
*
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
http://www.leetcode.com/wp-content/uploads/2012/04/histogram.png Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
http://www.leetcode.com/wp-content/uploads/2012/04/histogram_area.png The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.
*
*/
public class S84 {

public static void main(String[] args) {
int[] height = {2,1,2};
System.out.println(largestRectangleArea(height));
}

public static int largestRectangleArea(int[] height) {
if(height.length == 0){
return 0;
}
Stack<Integer> heightStack = new Stack<Integer>();
Stack<Integer> indexStack = new Stack<Integer>();

heightStack.push(height[0]);
indexStack.push(0);

int max = height[0];
for(int i=1; i<height.length; i++){
/*
#1: current Larger than previous (top of height stack)
Push current height & index as candidate rectangle start position
*/
if(heightStack.isEmpty() || height[i] > heightStack.peek()){
heightStack.push(height[i]);
indexStack.push(i);
}
/*
#3: current is less than previous
Need keep popping out previous heights, and compute the candidate rectangle with height and width (current index MINUS previous index)
Push the height and index (appropriate position) to stacks
*/
else if(height[i] < heightStack.peek()){
int lastIndex = 0; // used to keep track of last index which will be replacing the current index for current height inserting
while(!heightStack.isEmpty() && height[i]<heightStack.peek()){
lastIndex = indexStack.pop();
int h = heightStack.pop();
int w = i - lastIndex;
max = Math.max(max, h*w);
}
heightStack.push(height[i]);
indexStack.push(lastIndex); // Here should be lastIndex, one example: [2,1,2] => if lastIndex:3, if i:2
}
}

// deal with remaining elements in the stack
while(!heightStack.isEmpty()){
int lastIndex = indexStack.pop();
int h = heightStack.pop();
int w = height.length - lastIndex;
max = Math.max(max, h*w);
}

return max;
}

// TLE
public static int largestRectangleArea2(int[] height) {
int max = 0;
int len = height.length;
for(int i=0; i<len; i++){
int minHeight = height[i];
for(int j=i; j<len; j++){
minHeight = Math.min(minHeight, height[j]);
max = Math.max(max, (j-i+1)*minHeight);
}
}
return max;
}

}


这道题可以用
1 暴力法: O(n2) TLE
2 线段树:O(nlogn) StackOverflow
3 栈 AC

线段树:
public class LargestRect {

public static void main(String[] args) {
int[] height = {2,1,5,6,2,3};
System.out.println(largestRectangleArea(height));
}

public static int largestRectangleArea(int[] height) {
if(height.length == 0) {
return 0;
}
SegmentTree segmentTree = new SegmentTree(height.length);
segmentTree.constructSegmentTree(height);
return getMaxAreaRec(height, segmentTree, 0, height.length-1);
}

public static int getMaxAreaRec(int[] height, SegmentTree segmentTree, int arrayStartIdx, int arrayEndIdx) {
if(arrayStartIdx > arrayEndIdx) {
return -1;
}
if(arrayStartIdx == arrayEndIdx) {
return height[arrayStartIdx];
}

int minIndex = segmentTree.getMin(height, arrayStartIdx, arrayEndIdx);

return max(getMaxAreaRec(height, segmentTree, arrayStartIdx, minIndex-1),
getMaxAreaRec(height, segmentTree, minIndex+1, arrayEndIdx),
(arrayEndIdx-arrayStartIdx+1) * height[minIndex]);
}

public static int max(int a, int b, int c) {
return Math.max(Math.max(a, b), c);
}

public static class SegmentTree {
public int[] tree;		// store index to the minimum element in the range
private int treesize;
private int height;

private final int ARRAY_START_INDEX = 0;
private final int ARRAY_END_INDEX;
private final int TREE_ROOT_INDEX = 0;

public SegmentTree(int arraySize) {
ARRAY_END_INDEX = arraySize - 1;
height = (int)(Math.ceil(Math.log(arraySize)/Math.log(2)));
treesize = 2 * (int)Math.pow(2, height) - 1;
tree = new int[treesize];
}

// Find left child index of current node idx in tree
private int leftchild(int treeIdx) {
return 2*treeIdx + 1;
}

// Find right child index of current node idx in tree
private int rightchild(int treeIdx) {
return 2*treeIdx + 2;
}

// Find middle index from arrayStartIdx to arrayEndIdx in array
private int mid(int arrayStartIdx, int arrayEndIdx) {
return arrayStartIdx + (arrayEndIdx-arrayStartIdx)/2;
}

// construct segment tree
public void constructSegmentTree(int[] array) {
constructSegmentTreeUtil(array, ARRAY_START_INDEX, ARRAY_END_INDEX, TREE_ROOT_INDEX);
}

// return value of the node in treeRootIdx
private int constructSegmentTreeUtil(int[] array, int arrayStartIdx, int arrayEndIdx, int treeRootIdx) {
if(arrayStartIdx == arrayEndIdx) {		// single element in array
tree[treeRootIdx] = arrayStartIdx;	// save index instead of value!
return tree[treeRootIdx];
}
int arrayMidIdx = mid(arrayStartIdx, arrayEndIdx);
tree[treeRootIdx] = lesserByArrayIndex(array, constructSegmentTreeUtil(array, arrayStartIdx, arrayMidIdx, leftchild(treeRootIdx)),
constructSegmentTreeUtil(array, arrayMidIdx+1, arrayEndIdx, rightchild(treeRootIdx)));
return tree[treeRootIdx];
}

// get the one who is smaller in term of array value
private int lesserByArrayIndex(int[] array, int arrayIdx1, int arrayIdx2) {
if(arrayIdx1 == -1) 	return arrayIdx2;
if(arrayIdx2 == -1)		return arrayIdx1;
return array[arrayIdx1] < array[arrayIdx2] ? arrayIdx1 : arrayIdx2;
}

// get minimum index from a query range
public int getMin(int[] array, int arrayQueryStartIdx, int arrayQueryEndIdx) {
if(arrayQueryStartIdx < ARRAY_START_INDEX || arrayQueryEndIdx > ARRAY_END_INDEX || arrayQueryStartIdx > arrayQueryEndIdx) {
return -1;
}
return getMinUtil(array, ARRAY_START_INDEX, ARRAY_END_INDEX, arrayQueryStartIdx, arrayQueryEndIdx, TREE_ROOT_INDEX);
}

private int getMinUtil(int[] array, int arrayStartIdx, int arrayEndIdx, int arrayQueryStartIdx, int arrayQueryEndIdx, int treeRootIdx) {
if(arrayQueryStartIdx <= arrayStartIdx && arrayQueryEndIdx >= arrayEndIdx) {	// tree node is within query range, return query value
return tree[treeRootIdx];
}
if (arrayEndIdx < arrayQueryStartIdx || arrayStartIdx > arrayQueryEndIdx) {
return -1;		// not considered
}
int arrayMidIdx = mid(arrayStartIdx, arrayEndIdx);
return lesserByArrayIndex(array, getMinUtil(array, arrayStartIdx, arrayMidIdx, arrayQueryStartIdx, arrayQueryEndIdx, leftchild(treeRootIdx)),
getMinUtil(array, arrayMidIdx+1, arrayEndIdx, arrayQueryStartIdx, arrayQueryEndIdx, rightchild(treeRootIdx)));
}
}

}

具体解释参考:http://www.cnblogs.com/TenosDoIt/p/3453089.html
其他: http://www.sanfoundry.com/java-program-implement-segment-tree/ http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/ http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
栈:
关键两点:
1 栈里的元素总是上升的
2 在出栈时,如何找到出栈元素的前一个比它小的元素(s.peek())和出栈元素的后一个比它小的元素(i)
import java.util.*;
public class Solution {
public static int largestRectangleArea(int[] height) {
Stack<Integer> s = new Stack<Integer>();
int maxArea = 0;
int top;
int areaWithTop;

int i = 0;
while(i < height.length) {
if(s.isEmpty() || height[s.peek()] <= height[i]) {  // maintain ascending order!
s.push(i);
i++;
} else {
top = s.pop();
// previous one which is smaller: i, next one which is smaller: s.peek()
areaWithTop = height[top] * (s.isEmpty() ? i : i-s.peek()-1);
maxArea = Math.max(maxArea, areaWithTop);
}
}

while(!s.isEmpty()) {
top = s.pop();
areaWithTop = height[top] * (s.isEmpty() ? i : i-s.peek()-1);
maxArea = Math.max(maxArea, areaWithTop);
}

return maxArea;
}
}
http://www.geeksforgeeks.org/largest-rectangle-under-histogram/ http://blog.csdn.net/doc_sgl/article/details/11805519
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐