LeetCode LRU Cache

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.

题解:

写一个类来实现LRU算法,也就是系统中的页面最近最少使用算法,将最近最少使用的页面置换出去。那么在java中,其实是采用一个LinkedHashMap来实现的,既可以保证输入的顺序是按照插入的顺序,又可以保证在删除的时候是O(1)的时间复杂度。因为LinkedHashMap是一个双向链表来存储的。

class Node              //定义一个Node类,有一个指向前一个节点的pre和指向后一个节点的next
{
	int key;
	int value;
	Node pre;
	Node next;
	public Node(int key,int value)
	{
		this.key = key;
		this.value = value;
	}
}

public class LRUCache 
{
	int capacity;    //hashMap的默认容量
	Map<Integer,Node> hashMap = new HashMap<Integer,Node>();  //hashMap的结构,用一个Integer表示key值
	Node head = null;
	Node end = null;
	public LRUCache(int capacity)
	{
		this.capacity = capacity;
	}
	public void remove(Node n)
	{
		if(n.pre != null)  //因为这里保证了在hashMap中的每个node的key是不一样的,所以就可以直接找到
		{
			n.pre.next = n.next;
		}
		else
			head = n.next;
		if(n.next != null)
			n.next.pre = n.pre;
		else
			end = n.pre;
	}
	public void setHead(Node n)   //每次原来的页面重新被访问后,又将放到双向链表的头位置
	{
		n.next = head;
		n.pre = null;
		if(head != null)
			head.pre = n;
		head = n;
		if(end == null)
			end = head;
	}
	public int get(int key)
	{
		if(hashMap.containsKey(key))
		{
			Node n = hashMap.get(key);
			remove(n);
			setHead(n);
			return n.value;
		}
		return -1;
	}
	public void set(int key,int value)
	{
		if(hashMap.containsKey(key))
		{
			Node old = hashMap.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		}
		else
		{
			Node created = new Node(key,value);
			if(hashMap.size() >= capacity)
			{
				hashMap.remove(end.key);
				remove(end);
				setHead(created);
			}
			else
				setHead(created);
			hashMap.put(key, created);
		}
	}
}
此题阿里面试的时候又被问到,而在LeetCode居然有这题,说来也巧合,如果做过这题再去面阿里,估计就妥妥的了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值