//Given an array A[i..j] find out maximum j-i such that A[i]<a[j] in
//O(n) time
struct REC
{
int nIndex;
int nVal;
};
bool lessThan(const REC& rec1, const REC& rec2)
{
return rec1.nVal < rec2.nVal;
}
//sort the array by value.go through the array, find
//the max gap of two indexes
int GetRes(int a[], int n)
{
REC* recs = new REC[n];
for (int i = 0; i < n; i++)
{
recs[i].nIndex = i;
recs[i].nVal = a[i];
}
sort(recs, recs+n, lessThan);
int nMinIndex = recs[0].nIndex;
int nRet = 0;
for(int i = 1; i < n; i++)
{
if (recs[i].nIndex > nMinIndex)
nRet = max(nRet, recs[i].nIndex-nMinIndex);//如果下标大于nMinIndex,就要计算下gap
else
nMinIndex = recs[i].nIndex;//如果遇到比nMinIndex小的下标,就更新最小下标。这是因为数组已经按照从小到大排序,所以只要找到最小下标,
}
delete []recs;
return nRet;
}
//O(n) solution
int GetLongestDist(int a[], int n)
{
if (a == NULL || n <= 0)
return -1;
vector<int> vec;
for (int i = 0; i < n; i++)//存储最先遇到的最小值的下标,可以得出,求得的gap(i,j)中的i,肯定在vec中。可以通过反证法证明。
{
if (vec.empty() || a[i] < a[vec.back()])
vec.push_back(i);
}
int nRet = -1;
int i = vec.size()-1;
int j = n-1;
while (i >= 0)//通过两个指针,一个指向数组,一个指向vec
{
while (a[j] <= a[vec[i]] && j > vec[i])
j--;
if (j > vec[i])
nRet = max(nRet, j-vec[i]);
i--;
}
return nRet;
}
第三种算法的时间复杂度是o(nlogn)
用一个数组b[i]记录a[0]...a[i]的最小值
所以b[]是不上升数组
对a中的每一个值a[i]用二分查找法,在b中查找小于a[i]的最大的值,计算gap