前言
说实在的,感觉这种设计数据结构的题比链表题还要ex,尤其是当哈希表和链表一起上的时候!
一、设计有setAll功能的哈希表
#include <bits/stdc++.h>
using namespace std;
int cnt=0,setAllTime=0,setAllValue;
map<int,pair<int,int> >mySet;
void put(int x,int y)
{
mySet[x]={y,cnt};
}
void get(int x)
{
map<int,pair<int,int> >::iterator iter=mySet.find(x);
if(iter==mySet.end())
{
cout<<-1<<endl;
}
else
{
if(mySet[x].second<setAllTime)
{
cout<<setAllValue<<endl;
}
else
{
cout<<mySet[x].first<<endl;
}
}
}
int main()
{
int n;
cin>>n;
int opt,x,y;
for(int i=0;i<n;i++)
{
cin>>opt;
if(opt==1)
{
cin>>x>>y;
put(x,y);
cnt++;
}
else if(opt==2)
{
cin>>x;
get(x);
}
else
{
cin>>x;
setAllTime=cnt++;
setAllValue=x;
}
}
}
这个题若是不要求O(1),setAll时直接全改一遍就行了。但这里要求时间复杂度为O(1),所以要想新的思路。
这里引入“时间戳”的方法。每加入一个元素,让cnt++,模拟时间。之后若是有setAll的操作,就记下此时的时间,只有在拿数据的时候,若是该元素的加入时间在setAllTime之前,才输出setAll时的值。这样直接对结果操作就避免了把每个数据刷一遍。
二、LRU 缓存
class LRUCache {
public:
struct doubleList
{
int key;
int val;
doubleList* last;
doubleList* next;
};
map<int,doubleList*>m;
doubleList* head=NULL;
doubleList* tail=NULL;
int cap;
LRUCache(int capacity) {
cap=capacity;
}
void add(doubleList* node)
{
if(node==NULL)
{
return ;
}
if(head==NULL)
{
head=node;
tail=head;
}
else
{
tail->next=node;
node->last=tail;
tail=tail->next;
}
}
void move(doubleList* node)
{
if(node==tail)
{
return ;
}
if(node==head)
{