class Solution {
public :
vector< int > dailyTemperatures ( vector< int > & temperatures) {
stack< int > st;
vector< int > T ( temperatures. size ( ) , 0 ) ;
st. push ( 0 ) ;
for ( int i = 1 ; i < T. size ( ) ; i++ ) {
if ( temperatures[ i] <= temperatures[ st. top ( ) ] ) {
st. push ( i) ;
} else {
while ( ! st. empty ( ) && temperatures[ i] > temperatures[ st. top ( ) ] ) {
T[ st. top ( ) ] = i - st. top ( ) ;
st. pop ( ) ;
}
st. push ( i) ;
}
}
return T;
}
} ;
小结
通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。
class Solution {
public :
vector< int > nextGreaterElement ( vector< int > & nums1, vector< int > & nums2) {
vector< int > result ( nums1. size ( ) , - 1 ) ;
if ( nums1. size ( ) == 0 ) {
return result;
}
unordered_map< int , int > unmap;
for ( int i = 0 ; i < nums1. size ( ) ; i++ ) {
unmap[ nums1[ i] ] = i;
}
stack< int > st;
st. push ( 0 ) ;
for ( int i = 1 ; i < nums2. size ( ) ; i++ ) {
while ( ! st. empty ( ) && nums2[ i] > nums2[ st. top ( ) ] ) {
if ( unmap. count ( nums2[ st. top ( ) ] ) > 0 ) {
int index = unmap[ nums2[ st. top ( ) ] ] ;
result[ index] = nums2[ i] ;
}
st. pop ( ) ;
}
st. push ( i) ;
}
return result;
}
} ;
小结
错误在在构建单调栈时,无论是否记录结果,栈顶该pop就要pop
class Solution {
public :
vector< int > nextGreaterElements ( vector< int > & nums) {
vector< int > nums1 ( nums. begin ( ) , nums. end ( ) ) ;
nums. insert ( nums. end ( ) , nums1. begin ( ) , nums1. end ( ) ) ;
vector< int > result ( nums. size ( ) , - 1 ) ;
if ( result. size ( ) == 0 ) {
return result;
}
stack< int > st;
st. push ( 0 ) ;
for ( int i = 1 ; i < nums. size ( ) ; i++ ) {
while ( ! st. empty ( ) && nums[ i] > nums[ st. top ( ) ] ) {
result[ st. top ( ) ] = nums[ i] ;
st. pop ( ) ;
}
st. push ( i) ;
}
result. resize ( nums. size ( ) / 2 ) ;
return result;
}
} ;
小结
class Solution {
public :
int trap ( vector< int > & height) {
stack< int > st;
st. push ( 0 ) ;
int sum = 0 ;
for ( int i = 1 ; i < height. size ( ) ; ++ i) {
if ( height[ st. top ( ) ] == height[ i] ) {
st. pop ( ) ;
st. push ( i) ;
}
else if ( height[ st. top ( ) ] > height[ i] ) {
st. push ( i) ;
}
else {
while ( ! st. empty ( ) && height[ st. top ( ) ] < height[ i] ) {
int mid = st. top ( ) ;
st. pop ( ) ;
if ( ! st. empty ( ) ) {
int h = min ( height[ st. top ( ) ] , height[ i] ) - height[ mid] ;
int w = i - st. top ( ) - 1 ;
sum + = h * w;
}
}
st. push ( i) ;
}
}
return sum;
}
} ;
小结
class Solution {
public :
int largestRectangleArea ( vector< int > & heights) {
int result = 0 ;
stack< int > st;
st. push ( 0 ) ;
heights. insert ( heights. begin ( ) , 0 ) ;
heights. push_back ( 0 ) ;
for ( int i = 1 ; i < heights. size ( ) ; ++ i) {
while ( ! st. empty ( ) && heights[ st. top ( ) ] > heights[ i] ) {
int mid = st. top ( ) ;
st. pop ( ) ;
if ( ! st. empty ( ) ) {
int h = heights[ mid] ;
int w = i - st. top ( ) - 1 ;
result = max ( result, h * w) ;
}
}
st. push ( i) ;
}
return result;
}
} ;
小结