// No. 76
stringminWindow(strings,stringt){intstartId=0;intrightId=0;intminLen=s.length()+1;intleft=0,right=0;intmatchCount=0;// record the only need characters
unordered_map<char,int>window;unordered_map<char,int>need;for(autoch:t)need[ch]++;while(right<s.length()){autorch=s[right];right++;if(need.count(rch)){// expand window
window[rch]++;if(window[rch]==need[rch]){matchCount++;}}// shrink the window
while(matchCount==need.size()){if(right-left<minLen){startId=left;rightId=right;minLen=right-left;}autolch=s[left];if(need.count(lch)){window[lch]--;if(window[lch]<need[lch]){matchCount--;}}left++;}}returnrightId-startId>0?s.substr(startId,rightId-startId):"";}
intsubarraysWithKDistinct(vector<int>&A,intK){intleft=0,right=0;unordered_map<int,int>window;intcount=0;while(right<A.size()){autornum=A[right];window[rnum]++;right++;while(window.size()>K){autolnum=A[left];window[lnum]--;if(window[lnum]==0){window.erase(lnum);}left++;}inttmpLeft=left;while(window.size()==K){count++;window[A[tmpLeft]]--;if(window[A[tmpLeft]]==0){window.erase(A[tmpLeft]);}tmpLeft++;}// recover the window
while(tmpLeft>left){window[A[tmpLeft-1]]++;tmpLeft--;}}returncount;}
// C++ program to demonstrate functionality of unordered_map
#include<iostream>#include<unordered_map> //usingnamespacestd;intmain(){// Declaring umap to be of <string, int> type
// key will be of string type and mapped value will
// be of double type
unordered_map<string,int>umap;// inserting values by using [] operator
umap["GeeksforGeeks"]=10;umap["Practice"]=20;umap["Contribute"]=30;// Traversing an unordered map
for(autox:umap)cout<<x.first<<" "<<x.second<<endl;}
// C++ program to demonstrate functionality of unordered_map
#include<iostream>#include<unordered_map>usingnamespacestd;intmain(){// Declaring umap to be of <string, double> type
// key will be of string type and mapped value will
// be of double type
unordered_map<string,double>umap;// 新增键值对
umap["PI"]=3.14;umap["root2"]=1.414;umap["root3"]=1.732;umap["log10"]=2.302;umap["loge"]=1.0;// 插入键值对,可以使用c++的make_pair函数
umap.insert(make_pair("e",2.718));stringkey="PI";// 查询方法一
if(umap.find(key)==umap.end())cout<<key<<" not found\n\n";// If key found then iterator to that key is returned
elsecout<<"Found "<<key<<"\n\n";// 查询方法二
if(umap.count(key)==0)cout<<key<<" not found\n\n";// If key found then iterator to that key is returned
elsecout<<"Found "<<key<<"\n\n";// 遍历方法一
unordered_map<string,double>::iteratoritr;cout<<"\nAll Elements : \n";for(itr=umap.begin();itr!=umap.end();itr++){// itr works as a pointer to pair<string, double>
// type itr->first stores the key part and
// itr->second stroes the value part
cout<<itr->first<<" "<<itr->second<<endl;}// 遍历方法二
for(autoiter:umap){cout<<iter.first<<" "<<iter.second<<endl;}return0;}