两数组包含问题
来源:互联网 发布:手机百度软件exscl 编辑:程序博客网 时间:2024/05/17 09:31
题目:
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,windowmapfor (; 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和sameElementfor (i = lens; i < lenl; ++i){// 滑动窗口左侧划出的元素El在diffmap中, 更新diffmap和sameElementif (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和sameElementif (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;}
- 两数组包含问题
- 两数组包含问题
- 数组包含问题
- 面试题精选(87):两数组包含问题(来自微软面试题)
- 两数组最小距离问题
- JS两数组对比问题
- 两数组中项问题
- 数组包含
- 问题七十六: 两数组最短距离。
- 问题 A: 两数组最短距离
- include 两种包含
- 两种方法在Django框架中支持后台返回包含中文的JSON/数组格式
- 字符串包含问题的求解(最简单的方法——只有两行代码)
- 分治策略 求两同长数组的中位数问题
- LeetCode 题目之 数组两数之和问题
- 两道“诡异”的数组越界问题的分析
- jsp两种包含方式
- jsp两种包含方式
- Ubuntu常用命令
- C/S B/S架构
- 正则表达式在文本工具中的应用
- Java学习之InputStream中read()与read(byte[] b)
- misc creature 改变世界的24个发明
- 两数组包含问题
- class_create()
- 小菜开始学习算法(返璞归真->程序=数据结构+算法)
- Android屏幕适配不同的资源图片和布局
- hdu-1049 Climbing Worm
- misc life 未来的购物方式
- 提高生活、学习、工作效率的方法——时间管理Vs个人管理
- JavaScript笔记之操作Cookie
- C++中头文件(.h)和源文件(.cpp)都应该写些什么