题目:
代码:
class Solution {
public:
int longestMountain(vector<int>& A) {
int n=A.size();
if(n==0) return 0;
int danzeng[n],danjian[n];
danzeng[0]=1;
danjian[n-1]=1;
for(int i=1;i<n;i++){
if(A[i]>A[i-1]){
danzeng[i]=danzeng[i-1]+1;
}
else danzeng[i]=1;
}
for(int i=n-2;i>=0;i--){
if(A[i]>A[i+1]){
danjian[i]=danjian[i+1]+1;
}
else danjian[i]=1;
}
int ans=0;
for(int i=0;i<n;i++){
if(danzeng[i]>=2&&danjian[i]>=2){
ans=max(ans,danzeng[i]+danjian[i]-1);
}
}
return ans;
}
};
官方代码:(空间复杂度O(1))
class Solution {
public:
int longestMountain(vector<int>& A) {
int n = A.size();
int ans = 0;
int left = 0;
while (left + 2 < n) {
int right = left + 1;
if (A[left] < A[left + 1]) {
while (right + 1 < n && A[right] < A[right + 1]) {
++right;
}
if (right < n - 1 && A[right] > A[right + 1]) {
while (right + 1 < n && A[right] > A[right + 1]) {
++right;
}
ans = max(ans, right - left + 1);
}
else {
++right;
}
}
left = right;
}
return ans;
}
};
实际测起来两个代码消耗差不多?