面试题精选(87):两数组包含问题(来自微软面试题)
来源:互联网 发布:mac os x 10.3虚拟机 编辑:程序博客网 时间:2024/05/02 00:10
题目:
You have given two arrays, say
answer is (1,5) 先给出代码,再结合代码解释,如下:
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).
思路:
ex,
int A[] = {4, 1, 2, 1, 8, 9, 5, 3, 2, 9, 8, 4, 6};
int B[] = {1, 1, 2, 8, 9};
int lenA = 13;
int lenB = 5;
map<int,int> bmap;
map<int,int> windowmap;
map<int,int> diffmap;
首先初始化map:
bmap = {1:2, 2:1, 8:1,9:1}
windowmap = {1:2, 2:1, 4:1,8:1}
diffmap = {1:0, 2:0, 8:0, 9:-1}
其中"1: 0" 意味着数组A的当前滑动窗口正好和数组B包含相同数量的"1",而 " 9:-1" 则表示A当前的滑动窗口和B比较缺少1个"9"。 并且我们注意到diffmap和bmap拥有相同的key
代码中的变量"sameElement"代表的是diffmap中有多少pair与bmap匹配, 显然,初始化后的“sameElement”变量值会是3 ( 1:0, 2:0, 8:0 in diffmap).
接下来
在数组A中滑动size为lenB的窗口,没向前滑动一步,只需check滑动窗口左侧划出的元素El和右侧滑入的元素Er,更新diffmap和sameElement,如下:
if(diffmap.count(A[i-lenB]) != 0)
{
diffmap[A[i-lenB]]--;
if(diffmap[A[i-lenB]] == 0)
sameElement++;
else if(diffmap[A[i-lenB]] == -1)
sameElement--;
}
if(diffmap.count(A[i]) !=0)
{
diffmap[A[i]]++;
if(diffmap[A[i]] == 0)
sameElement++;
else if(diffmap[A[i]] == 1)
sameElement--;
}
if(sameElement == diffmap.size())
{
cout<<"----------find one---------"<<endl;
cout<<"start index:"<<i-lenB+1<<endl;
cout<<"end index:"<<i+1<<endl;
}
- 面试题精选(87):两数组包含问题(来自微软面试题)
- [面试题精选]微软试题
- 面试题精选(81):两道按照要求重排数组问题
- 面试题精选(一)
- 面试题精选(二)
- 面试题精选(77):两有序数组的中位数求解
- 北美微软面试题---数组问题
- 程序员面试题精选(33):两单向链表相交问题
- 两道微软面试题
- 微软面试题(二)
- 微软面试题(一)
- 微软面试题(二)
- 微软面试题(三)
- 微软面试题(四)
- 微软面试题(转载)
- 微软面试题(收集)
- 程序员面试题精选(23):跳台阶问题
- 面试题精选(70):100人民币问题
- Oracle小技巧
- printf输出格式 收藏
- 购物车的实现方案
- printf输出格式 收藏1
- 第七天:NBT Name Service 包格式解析
- 面试题精选(87):两数组包含问题(来自微软面试题)
- Java类文件解析
- js 替换文本
- 请没有买房和买车的朋友一定认真的看一下,看后再做决定吧...
- 百度面试
- Delphi建立精确计时器
- c++运算符优先级列表
- vs2005安装opengl
- MVC HtmlHelper类的方法总结