Find the smallest window of a certain sequence

本文介绍了一种算法,该算法接收两个整数数组作为输入:一个是大小为n的输入数组,另一个是大小为k的查询数组。目标是找出输入数组中包含查询数组所有元素的最小子序列,并且这些元素在子序列中的顺序与查询数组相同。

http://haixiaoyang.wordpress.com/2012/03/25/find-the-smallest-window-of-a-certain-sequence/

//Given an input array of integers of size n, and a query array of 
//integers of size k, find the smallest window of input array that 
//contains all the elements of query array and also in the same order

int GetMinOrder(int a[], int n, int b[], int m)
{
	assert(a && n > 0 && b && m > 0 && n >= m);

	int nMin = -1;
	for (int i = 0; i < n; i++)
	{
		if (a[i] != b[0]) continue;

		int nCur = 0;
		int j = i;
		for (; j < n && nCur < m; j++)
		{
			if (a[j] == b[nCur])
				nCur++;
		}

		if (nCur == m)
			nMin = nMin < 0 ? (j - i) : min(nMin, (j-i));
		else break;
	}

	return nMin;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值