leetcode_Design and implement a data structure for Least Recently Used (LRU) cache

    /*
     * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
     * */
	public class LRUCache
	{
		
		private Map<Integer, MapNode> map = null;
		private int capacity;
		private int size;
		public LRUCache(int capacity)
		{
			this.capacity = capacity;
			size = 0;
			map = new LinkedHashMap<Integer,MapNode>();
		}

		public int get(int key)
		{
			if(map.containsKey(key) == false)
			{
				return -1;
			}
			else 
			{
				int r = map.get(key).value;
				
				//adjust the position of this item
				MapNode tmMapNode = map.get(key);
				map.remove(key);
				map.put(key, tmMapNode);
				return r;
			}
		}

		public void set(int key, int value)
		{
			if(map.containsKey(key)==false)
			{
				if(size<capacity)
				{
					map.put(new Integer(key), new MapNode(key, value));
					size++;					
				}
				else 
				{
					//if size capacity is zero , does this still work correctly?
					//delete the first one which is the least used one
					Iterator<Entry<Integer, MapNode>> iterator= map.entrySet().iterator();
					Integer tmp = null;
					if(iterator.hasNext())
					{
						tmp = iterator.next().getKey();
//						map.remove(tmp); 
//						map.put(new Integer(key), new MapNode(key, value)); 
					}
					if(tmp != null)
					{
						map.remove(tmp); 
						map.put(new Integer(key), new MapNode(key, value)); 
					}
					
				}
			}
			else 
			{
				//delete this node and change its content then add it,make it the last one
				MapNode tmpMapNode =  map.get(new Integer(key));
				map.remove(new Integer(key));
				tmpMapNode.value = value;
				map.put(new Integer(key), tmpMapNode);
			}
		}
		
		public class MapNode
		{
			int key;
			int value;
			public MapNode(int k, int v)
			{
				key = k;
				value = v;
			}
		}
	} 

总结延伸://各种容器使用 map hashmap 等 他们操作的复杂度?,这里使用的LinkedHashMap其中数据保持插入顺序,后进的在头部

(notice that java.util.LinkedHashMap uses insertion-order.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值