Skip to content

Commit c25120b

Browse files
authored
Create LRU缓存机制.cpp
1 parent e0819c7 commit c25120b

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed

LRU缓存机制.cpp

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
//https://leetcode-cn.com/explore/interview/card/bytedance/245/data-structure/1032/
2+
//运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
3+
//获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
4+
//写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
5+
//思路:使用一个链表,链表长度最长位k。每次get的时候找得到就返回value,找不到就返回-1;每次put的时候,首先看是否有key,有就替换,没有就查看是否超出长度限制,超出的话删除最后一位并在头部插入key,value
6+
//其中符合LRU思路的就是每次操作完一个位置,就把这个位置提到链表的头部。
7+
8+
9+
class LRUCache {
10+
public:
11+
struct lists{
12+
int key;
13+
int value;
14+
lists *next;
15+
lists(int k,int v):key(k),value(v),next(NULL){}
16+
};
17+
lists* l;
18+
int k;
19+
LRUCache(int capacity) {
20+
k=capacity;
21+
l=NULL;
22+
}
23+
24+
// void print1(lists* ll){
25+
// lists *index=ll;
26+
// while(index!=NULL){
27+
// cout<<index->key<<'-'<<index->value<<' ';
28+
// index=index->next;
29+
// }
30+
// cout<<endl;
31+
// }
32+
33+
int get(int key) {
34+
//print1(l);
35+
if(l==NULL){
36+
return -1;
37+
}
38+
lists *index=l;
39+
if(l->key==key){
40+
return l->value;
41+
}
42+
while(index->next!=NULL){
43+
if(index->next->key==key){
44+
int v=index->next->value;
45+
index->next=index->next->next;
46+
lists *temp=l;
47+
l=new lists(key,v);
48+
l->next=temp;
49+
return v;
50+
}else{
51+
index=index->next;
52+
}
53+
}
54+
return -1;
55+
}
56+
57+
58+
void put(int key, int value) {
59+
bool flag=false;
60+
if(l==NULL){
61+
l=new lists(key,value);
62+
return;
63+
}
64+
if(l->key==key){
65+
l->value=value;
66+
return;
67+
}
68+
lists *index=l;
69+
while(index->next!=NULL){
70+
if(index->next->key==key){
71+
index->next=index->next->next;
72+
flag=true;
73+
lists *temp=l;
74+
l=new lists(key,value);
75+
l->next=temp;
76+
//提到前面去
77+
}else{
78+
index=index->next;
79+
}
80+
}
81+
if(!flag){
82+
//插入
83+
int count=0;
84+
lists *temp=l;
85+
if(k==1){
86+
l=new lists(key,value);
87+
return;
88+
}
89+
while(temp!=NULL){
90+
count=count+1;
91+
if(count==k-1){
92+
temp->next=NULL;
93+
break;
94+
}
95+
temp=temp->next;
96+
}
97+
lists *t=l;
98+
l=new lists(key,value);
99+
l->next=t;
100+
}
101+
}
102+
};
103+
104+
/**
105+
* Your LRUCache object will be instantiated and called as such:
106+
* LRUCache* obj = new LRUCache(capacity);
107+
* int param_1 = obj->get(key);
108+
* obj->put(key,value);
109+
*/

0 commit comments

Comments
 (0)