大概就是理解【一个数据在最近没有被用到】且【不是新插入的】那么内存不足了就先淘汰的思想,然后配合php的数组来实现,就OK了。
<?php
class LRUCache {
public $capacity;
public $LRUArr=[];
function __construct($capacity) {
$this->capacity = $capacity;
}
function get($key) {
if(array_key_exists($key,$this->LRUArr)){
$tmp = $this->LRUArr[$key];
unset($this->LRUArr[$key]);
$this->LRUArr[$key]= $tmp;
return $tmp;
}
return -1;
}
function put($key, $value) {
if(array_key_exists($key,$this->LRUArr)){
unset($this->LRUArr[$key]);
}else{
$len =count($this->LRUArr);
if($len == $this->capacity){
foreach($this->LRUArr as $k=>$v){
unset($this->LRUArr[$k]);
break;
}
}
}
$this->LRUArr[$key]=$value;
}
}
$obj = new LRUCache(2);
$obj->put(1, 1);
$obj->put(2, 2);
$obj->get(1);
$obj->put(3, 3);
$obj->get(2);
$obj->put(4, 4);
$obj->get(1);
$obj->get(3);
$obj->get(4);
|