设计LRU实现get和put操作

本文介绍了如何在O(1)时间复杂度内,利用哈希数据结构设计LRU缓存,包括数组实现和使用STL中的unordered_map。文中提及该问题来源于LeetCode,并建议在编写代码前复习STL的相关知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题重在数据结构的使用,要求是o(1)的时间复杂度完成上面两个操作,自然想到了哈希。

第一种解法:用数组实现哈希

#include <vector>
#include <iostream>
#include <string.h>
using namespace  std;
//ector< vector<int> > A;
int A[8000] = {0};
int latest;
int count;
void get(int key )
{
   if(A[key] !=0)
   {
    cout << A[key] << endl;
   }
    else
    cout << -1 << endl;
}

void put(int key ,int val)
{
    A[key] = val;
    latest = key;
    count +=1;
}

int main()
{
    int num , m , n;
    //string s;
    char s ;
    cin >> num ;
    //cin >> s;
    while( cin >> s)
    {
    if( s == 'p')
    {
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值