题目:
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;
}