Given an array A[i..j] find out maximum j-i such that A[i]<a[j]

//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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值