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

本文介绍了一种高效算法来解决直方图中寻找最大矩形面积的问题。通过使用栈来跟踪高度和索引,该算法能在O(n)的时间复杂度内找到最大矩形面积。

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.youkuaiyun.com/doc_sgl/article/details/11805519








基于TROPOMI高光谱遥感仪器获取的大气成分观测资料,本研究聚焦于大气污染物一氧化氮(NO₂)的空间分布与浓度定量反演问题。NO₂作为影响空气质量的关键指标,其精确监测对环境保护与大气科学研究具有显著价值。当前,利用卫星遥感数据结合先进算法实现NO₂浓度的高精度反演已成为该领域的重要研究方向。 本研究构建了一套以深度学习为核心的技术框架,整合了来自TROPOMI仪器的光谱辐射信息、观测几何参数以及辅助气象数据,形成多维度特征数据集。该数据集充分融合了不同来源的观测信息,为深入解析大气中NO₂的时空变化规律提供了数据基础,有助于提升反演模型的准确性与环境预测的可靠性。 在模型架构方面,项目设计了一种多分支神经网络,用于分别处理光谱特征与气象特征等多模态数据。各分支通过独立学习提取代表性特征,并在深层网络中进行特征融合,从而综合利用不同数据的互补信息,显著提高了NO₂浓度反演的整体精度。这种多源信息融合策略有效增强了模型对复杂大气环境的表征能力。 研究过程涵盖了系统的数据处理流程。前期预处理包括辐射定标、噪声抑制及数据标准化等步骤,以保障输入特征的质量与一致性;后期处理则涉及模型输出的物理量转换与结果验证,确保反演结果符合实际大气浓度范围,提升数据的实用价值。 此外,本研究进一步对不同功能区域(如城市建成区、工业带、郊区及自然背景区)的NO₂浓度分布进行了对比分析,揭示了人类活动与污染物空间格局的关联性。相关结论可为区域环境规划、污染管控政策的制定提供科学依据,助力大气环境治理与公共健康保护。 综上所述,本研究通过融合TROPOMI高光谱数据与多模态特征深度学习技术,发展了一套高效、准确的大气NO₂浓度遥感反演方法,不仅提升了卫星大气监测的技术水平,也为环境管理与决策支持提供了重要的技术工具。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值