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

504 篇文章 0 订阅

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)


请同时参考  http://blog.csdn.net/yysdsyl/article/details/5421200

// 两数组包含问题(来自微软面试题).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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值