分享下头条第一题解法,同时求问第四题这类题该如何做
vector < int >res( 2 ,- 1 );
if (nums. size ()<= 2 ){
res[ 0 ]=- 1 ;
res[ 1 ]=- 1 ;
} else {
vector < int >dpDecrease(nums. size (), 1 ); // 序列到当前位的最长递减子串长度
vector < int >dpIncrease(nums. size (), 1 ); // 序列到当前位的最长递增子串长度
for ( int i= 1 ;i<nums. size ();++i){
if (nums[ i ]<nums[ i - 1 ]){
dpDecrease[ i ] = dpDecrease[ i - 1 ]+ 1 ;
dpIncrease[ i ] = 1 ;
} else {
dpIncrease[ i ] = dpIncrease[ i - 1 ]+ 1 ;
dpDecrease[ i ] = 1 ;
}
}
vector < int >len(nums. size (), 0 ); // 序列到当前位的最长 “ 先上升后下降 ” 区间长度
int max = 1 ;
int left = - 1 ,right=- 1 ;
for ( int i= 0 ;i<nums. size ();++i){
if (dpDecrease[ i ]== 1 ){
len[ i ]= 0 ;
} else {
int j = i - dpDecrease[ i ] + 1 ;
if (dpIncrease[ j ] == 1 ){
len[ i ] = 0 ;
} else {
len[ i ] = dpDecrease[ i ]+dpIncrease[ j ]- 1 ;
if (max<len[ i ]){
max = len[ i ];
left = j - dpIncrease[ j ]+ 1 ;
right = i;
}
}
}
}
res[ 0 ] = left;
res[ 1 ] = right;
}
return res;
}
#字节跳动#