[LeetCode]LRUcache题解(不使用STL容器)
来源:互联网 发布:安卓人肉软件 编辑:程序博客网 时间:2024/06/06 19:36
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
用链表实现的,没用使用map。感觉使用map有作弊的感觉。
#include <iostream>#include <stack>#include <vector>#include <string>#include <stdlib.h>#include <sstream>#include <algorithm>#include <map>using namespace std;class LRUCache{public: struct LinkNode { int key,val; LinkNode *next; LinkNode(int key,int value) : val(value) ,key(key), next(nullptr){} }; int size,capacity; LinkNode *head,*tail; LRUCache(int capacity) { this->capacity = capacity; this->size = 0; this->tail = this->head = nullptr; } int get(int key) { if(head == nullptr)return -1; LinkNode* p = head; if(head->key == key){ tail->next = head; tail = head; head = tail->next; tail->next = nullptr; return tail->val; } while (p->next != nullptr) { if(p->next->key == key){ tail->next = p->next; tail = p->next; p->next = tail->next; tail->next = nullptr; return tail->val; } p = p->next; } return -1; } void set(int key, int value) { LinkNode* p = head; if(p!=nullptr&&head->key == key){ tail->next = head; tail = head; tail->val = value; head = tail->next; tail->next = nullptr; return; } while (p!=nullptr&&p->next != nullptr) { if(p->next->key == key){ tail->next = p->next; tail = p->next; tail->val = value; p->next = tail->next; tail->next = nullptr; return; } p = p->next; } LinkNode* newnode = new LinkNode(key,value); if(size >= capacity) head = head->next; else ++size; if(head == nullptr) head = newnode; else tail->next = newnode; tail = newnode; return; }};int main(){ auto cache = new LRUCache(2); cache->set(1, 1); cache->set(2,2); cache->set(2,3); cout<<cache->get(2)<<endl; //system("pause"); }
0 0
- [LeetCode]LRUcache题解(不使用STL容器)
- LeetCode 146 LRUCache Python题解
- STL容器用法(不完整)
- 【拿来主义】STL容器使用
- STL容器使用总结
- STL容器使用总结
- STL容器的使用
- STL容器vector使用
- STL容器deque使用
- STL容器lists使用
- c++STL容器使用
- STL容器综合使用
- STL-list容器使用
- leetcode LRUCache
- Leetcode- LRUCache
- LRUCache---leetcode
- 使用STL容器构成一棵树
- 多线程中使用stl容器
- Oracle物化视图3 - Prebuilt MV
- Ubuntu 13.04 服务器版本系统安装图解教程
- Java程序员必知的常用工具集
- ZOJ-1068
- 详解iPhone应用程序 多语言支持操作
- [LeetCode]LRUcache题解(不使用STL容器)
- Server returned HTTP response code: 500 for URL
- coldblocks在linux下安装
- 手机轻轻松松的操作就能很好的记录下生活重的点点滴滴了
- 文档汇总
- 连接OPC服务器
- 改变控件颜色的方法
- for xml path
- 谈Android外包项目