版权声明:孔庆鑫 https://blog.csdn.net/kongqingxin12/article/details/85232113
超时解法1:
class Solution {
public:
int maxWidthRamp(vector<int>& A) {
int _slope=INTMAX_MIN;
pair<int,pair<int,int>> num;
int _max=*max_element(A.begin(),A.end());
int _min=*min_element(A.begin(),A.end());
map<int,pair<int,int>>_count;
_count[A[0]].first=-1;
//在A[i]==A[j]相同的情况下,最大的坡度
for (int i = 0; i <A.size() ; ++i)
{
if((_count[A[i]].first==0&&A[i]!=A[0])||i==0)
_count[A[i]].first=i;
else
_count[A[i]].second=i;
}
//找出最大坡度
for(auto i=_count.begin();i!=_count.end();i++)
{
pair<int,pair<int,int>>tmp=*i;
_slope=max(_slope,check(tmp,A));
}
return _slope;
}
int check(pair<int,pair<int,int>>tmp,vector<int>A)
{
int len_left=0,len_right=0;
for (int i = 0; i <tmp.second.first ; ++i) {
if(A[i]<tmp.first)
len_left=tmp.second.second-i;
}
for (int j = tmp.second.second; j <A.size() ; ++j) {
if(A[j]>tmp.first)
len_right=j-tmp.second.first;
}
if(len_left!=0||len_right!=0)
return max(len_left,len_right);
return tmp.second.second-tmp.second.first;
}
};
解题思路:第二天上班在做这道题的时候发现自己想复杂了;对于这道题而言,就是利用左右指针来求解,返回条件是宽度值大于右指针的值;
class Solution {
public:
int maxWidthRamp(vector<int>& A)
{
int slope=INTMAX_MIN;
for (int i = A.size()-1; i >-1 ; --i) {
int tmp=A[i];
for (int j = 0; j <i ; ++j) {
if(A[j]<=A[i]) {
slope = max(slope, i - j);
break;
}
}
if(slope>=i)
return slope;
}
}
};