数据结构与算法:数据结构设计相关题

前言

说实在的,感觉这种设计数据结构的题比链表题还要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)
        {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值