两数组包含问题

题目:

You have given two arrays, say


A: 4, 1, 6, 2, 8, 9, 5, 3, 2, 9, 8, 4, 6
B: 6, 1, 2, 9, 8

where B contains elements which are in A in consecutive locations but may be in any order.
Find their starting and ending indexes in A. (Be careful of duplicate numbers).

 

answer is (1,5)


code:

#include <iostream>
#include <map>
using namespace std;

void FindSubArr(int large[], int lenl, int small[], int lens)
{
	int i = 0;
	map<int, int> smallmap;
	map<int, int> windowmap;
	map<int, int> diffmap;

	// 初始化 smallmap,windowmap
	for (; i < lens; ++i)
	{
		if (0 == smallmap.count(small[i]))
		{
			smallmap[small[i]] = 1;
		}
		else
		{
			++smallmap[small[i]];
		}

		if (0 == windowmap.count(large[i]))
		{
			windowmap[large[i]] = 1;
		}
		else
		{
			++windowmap[large[i]];
		}
	}

	map<int, int>::iterator it = smallmap.begin();
	int sameElement = 0;

	// 初始化 diffmap, 和smallmap中有一样的key,但value不同。且smallmap.size()等于diffmap.size()。
	while (it != smallmap.end())
	{
		if (0 != windowmap.count((*it).first))
		{
			diffmap[(*it).first] = windowmap[(*it).first] - (*it).second;
			if (0 == diffmap[(*it).first])
			{
				++sameElement;
			}
		} 
		else
		{
			diffmap[(*it).first] -= (*it).second;
		}

		it++;
	}

	if (sameElement == smallmap.size())
	{
		cout << "----------find one---------" << endl;  
		cout << "start index:" << 0 << endl;  
		cout << "end index:" << lens - 1 << endl;  
	}

	// 在数组large中滑动size为lens的窗口,每向前滑动一步,只需check滑动窗口左侧划出的元素El和右侧滑入的元素Er,更新diffmap和sameElement
	for (i = lens; i < lenl; ++i)
	{
		// 滑动窗口左侧划出的元素El在diffmap中, 更新diffmap和sameElement
		if (0 != diffmap.count(large[i - lens]))
		{
			diffmap[large[i - lens]]--;
			if (0 == diffmap[large[i - lens]])
			{
				sameElement++;
			}
			else if (-1 == diffmap[large[i - lens]])
			{
				sameElement--;
			}
			else
			{

			}

		} 

		// 滑动窗口右侧滑入的元素Er在diffmap中, 更新diffmap和sameElement
		if (0 != diffmap.count(large[i]))
		{
			diffmap[large[i]]++;
			if (0 == diffmap[large[i]])
			{
				sameElement++;
			}
			else if (1 == diffmap[large[i]])
			{
				sameElement--;
			}
			else
			{

			}
		}

		if (sameElement == diffmap.size())
		{
			cout << "----------find one---------" << endl;  
			cout << "start index:" << i - lens + 1 << endl;  
			cout << "end index:" << i << endl; 
		}

	}


}

int main()
{
	int A[] = {4, 1, 2, 1, 8, 9, 2, 1, 2, 9, 8, 1, 4, 6};  
	int B[] = {1, 1, 2, 8, 9};  
	int lenA = sizeof(A)/sizeof(int);  
	int lenB = sizeof(B)/sizeof(int);  
	FindSubArr(A, lenA, B, lenB);  
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值