Mainly the use of priority_queue
One is the built-in type priority queue how to set the small Gan (the default large root heap)
If it's a custom data structure, there are two ways
1, the definition of this data structure of the comparison symbol, can be used as a built-in type integer
2, pass in an overloaded () class, when less than the number, the default or big root heap, perhaps passed in is a callable object is OK, I tried a function like not, do not understand, regardless of
LRU Cache
classlrucache{ Public: //@param capacity, an integer intTime ; typedefintkey; typedefintTime ; typedefintvalue; typedef pair<key,time>Ktpair; structCMP {BOOL operator() (Ktpair X1,ktpair x2) {returnX1.second >X2.second; } }; Map<key,value>kv; Map<key,time>kt; Priority_queue<ktpair,vector<ktpair>,cmp>Q; intCap; LRUCache (intcapacity) { //Write your code hereTime =0; Cap=capacity; } voidInsertintKeyintValueintTime ) {Kv[key]=value; Kt[key]=Time ; Q.push (Make_pair (key,time)); } //@return An integer int Get(intkey) { //Write your code heretime++; value ret; if(Kv.find (key)! =Kv.end ()) { intValue =Kv[key]; Insert (Key,value,time); returnvalue; } Else return-1; } //@param key, an integer//@param value, an integer//@return Nothing void Set(intKeyintvalue) { //Write your code heretime++; if(Kv.find (key) = =Kv.end ()) {Insert (key,value,time); if(!Cap) { for(;;) {Auto x=Q.top (); Auto Ckey=X.first; Auto CTime=X.second; Q.pop (); if(Kt.find (ckey) = = Kt.end () | | kt[ckey]! = CTime)Continue; Else{kv.erase (ckey); Kt.erase (Ckey); Break; } } } Elsecap--; } ElseInsert (key,value,time); }};
Data Stream Median
classSolution { Public: /** * @param nums:a list of integers. * @return: The median of numbers*/Vector<int> medianii (vector<int> &nums) { //Write your code herepriority_queue<int,vector<int>,less<int>>Q1; Priority_queue<int,vector<int>,greater<int>>Q2; Vector<int>ret; Q1.push (int_min); Q2.push (Int_max); for(Auto x:nums) {if(X <q2.top ()) Q1.push (x); ElseQ2.push (x); if(Q1.size () <q2.size ()) {Q1.push (Q2.top ()); Q2.pop (); } if(Q1.size () >1+q2.size ()) {Q2.push (Q1.top ()); Q1.pop (); } ret.push_back (Q1.top ()); } returnret; }};
"Lintcode" LRU Cache, Data Stream Median