您的位置:首页 > 职场人生

两数组包含问题(来自微软面试题)

2013-04-08 23:24 225 查看
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)

请同时参考 /article/2783248.html

// 两数组包含问题(来自微软面试题).cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <map>

using namespace std;

void FindConsecutiveSubstringLocator(int A[], int lenA, int B[], int lenB, int &Pos1, int &Pos2)
{
std::map<int,int> mapB;
std::map<int,int> mapWindow;

for (int idx = 0; idx < lenB; idx++)
{
if (mapB.count(B[idx]) == 0)
mapB[B[idx]] = 1;
else
mapB[B[idx]]++;
}

for (int i = 0; i <= lenA-lenB;)
{
int j = i;
for (; j < i+lenB; j++)
{
if (mapB.count(A[j]) > 0)
{
if (mapWindow.count(A[j]) == 0)
{
mapWindow[A[j]] = 1;
}
else
{
if (mapWindow[A[j]] < mapB[A[j]])
{
mapWindow[A[j]]++;
}
else
{
for (int k = i; k < j; k++)
{
if (A[k] == A[j])
{
i = k+1;
mapWindow.clear();
break;
}
}
break;
}
}
}
else
{
i++;
mapWindow.clear();
break;
}
}

if (j == i+lenB)
{
Pos1 = j-lenB;
Pos2 = j-1;

return;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[] = {4, 1, 2, 1, 8, 1, 8, 9, 2, 1, 2, 9, 8, 4, 6};
int B[] = {1, 1, 2, 8, 9};
int lenA = sizeof(A)/sizeof(int);
int lenB = sizeof(B)/sizeof(int);

int pos1 = 0, pos2 = 0;
FindConsecutiveSubstringLocator(A, lenA, B, lenB, pos1, pos2);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: