Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 40d75e1

Browse files
committed
Add solution 146.
1 parent 5787f2d commit 40d75e1

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
class Node{
2+
var $key;
3+
var $val;
4+
var $prev;
5+
var $next;
6+
function __construct($key, $val) {
7+
$this->key = $key;
8+
$this->val = $val;
9+
$this->prev = null;
10+
$this->next = null;
11+
}
12+
}
13+
14+
class LRUCache {
15+
/**
16+
* @param Integer $capacity
17+
*/
18+
function __construct($capacity) {
19+
$this->capacity = $capacity;
20+
$this->currentCapacity = 0;
21+
$this->head = new Node(0, 0);
22+
$this->tail = new Node(0, 0);
23+
$this->head->next = $this->tail;
24+
$this->tail->prev = $this->head;
25+
$this->map = [];
26+
}
27+
28+
/**
29+
* @param Integer $key
30+
* @return Integer
31+
*/
32+
function get($key) {
33+
if (array_key_exists($key, $this->map)) {
34+
$node = $this->map[$key];
35+
self::removeNode($node);
36+
self::addToTail($node);
37+
return $node->val;
38+
}
39+
return -1;
40+
}
41+
42+
/**
43+
* @param Integer $key
44+
* @param Integer $value
45+
* @return NULL
46+
*/
47+
function put($key, $value) {
48+
if (array_key_exists($key, $this->map)) {
49+
$node = $this->map[$key];
50+
self::removeNode($node);
51+
$node->val = $value;
52+
$this->map[$key] = $node;
53+
self::addToTail($node);
54+
} else {
55+
if ($this->currentCapacity == $this->capacity) {
56+
$removeKey = $this->head->next->key;
57+
self::removeNode($this->head->next);
58+
unset($this->map[$removeKey]);
59+
$this->currentCapacity--;
60+
}
61+
$newNode = new Node($key, $value);
62+
$this->map[$key] = $newNode;
63+
self::addToTail($newNode);
64+
$this->currentCapacity++;
65+
}
66+
}
67+
68+
function removeNode($node) {
69+
$node->prev->next = $node->next;
70+
$node->next->prev = $node->prev;
71+
}
72+
73+
function addToTail($node) {
74+
$this->tail->prev->next = $node;
75+
$node->prev = $this->tail->prev;
76+
$node->next = $this->tail;
77+
$this->tail->prev = $node;
78+
}
79+
80+
}
81+
82+
/**
83+
* Your LRUCache object will be instantiated and called as such:
84+
* $obj = LRUCache($capacity);
85+
* $ret_1 = $obj->get($key);
86+
* $obj->put($key, $value);
87+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /