LeetCode LRU Cache

题意:模拟实现LRU缓存,可以支持的功能有get(key)和set(key,value)

解法:

1、先来一个朴素的,自己模拟的双端队列,可惜TLE了,不过大家可以打打玩玩

public class LRUCache {
	int capacity;
	node head = null, tail = null;

	public LRUCache(int capacity) {
		this.capacity = capacity;
		head = new node(-1, -1);
		tail = new node(-1, -1);
		head.next = tail;
		tail.prev = head;
	}

	public int get(int key) {
		node tot = head;
		while (tot.key != key && tot != tail) {
			tot = tot.next;
		}
		if (tot == tail) {
			return -1;
		} else {
			int val = tot.val;
			set(key, val);
			return val;
		}
	}

	public void set(int key, int value) {
		node tot = head;
		int cnt = 0;
		while (tot.key != key && tot != tail) {
			tot = tot.next;
			cnt++;
		}
		if (tot == tail) {
			tot = new node(key, value);
			if (cnt == 1 + capacity) {
				node temp = tail.prev;
				temp.prev.next = tail;
				tail.prev = temp.prev;
			}
		} else {
			tot.val = value;
			tot.prev.next = tot.next;
			tot.next.prev = tot.prev;
		}
		node second = head.next;
		head.next = tot;
		tot.next = second;
		tot.prev = head;
		second.prev = tot;

	}

	public void print() {
		node tot = head;
		System.out.print("print :   ");
		while (tot != null) {
			System.out.printf("<%d,%d>   ", tot.key, tot.val);
			tot = tot.next;
		}
		System.out.println();
	}

	public void reverse_print() {
		node tot = tail;
		System.out.print("reverse print :   ");
		while (tot != null) {
			System.out.printf("<%d,%d>   ", tot.key, tot.val);
			tot = tot.prev;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		LRUCache lru = new LRUCache(1);
		lru.set(2, 1);
		lru.print();
		lru.reverse_print();
		System.out.println(lru.get(2));
		lru.set(3, 2);
		lru.print();
		System.out.println(lru.get(2));
		System.out.println(lru.get(3));
	}
}

class node {
	int key, val;
	node prev = null, next = null;

	node(int a, int b) {
		key = a;
		val = b;
	}
}


2、下面的反应就是如何更快,第一反应是用HashCode来解决,介绍一个类LinkedHashMap——解决LRU的神奇啊

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache {
	Map<Integer, Integer> map;

	public LRUCache(int capacity) {
		final int c = capacity;
		map = new LinkedHashMap<Integer, Integer>(c, 0.75f, true) {
			protected boolean removeEldestEntry(
					Map.Entry<Integer, Integer> eldest) {
				return size() > c;
			}
		};
	}

	public int get(int key) {
		if (map.containsKey(key)) {
			return map.get(key);
		} else
			return -1;
	}

	public void set(int key, int value) {
		map.put(key, value);
	}

	public static void main(String[] args) {
		LRUCache lru = new LRUCache(1);
		lru.set(2, 1);
		System.out.println(lru.get(2));
		lru.set(3, 2);
		System.out.println(lru.get(2));
		System.out.println(lru.get(3));
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值