码迷,mamicode.com
首页 > 系统相关 > 详细

[LeetCode]LRU Cache

时间:2015-12-03 02:14:07      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

public class LRUCache {
    HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>();
    ListNode start;
    ListNode end;
    int capacity;
    int cur_size;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        cur_size = 0;
        start = new ListNode(0);
        end = new ListNode(0);
        start.next = end;
        end.pre = start;
    }
    
    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        ListNode node = map.get(key);
        delete(node);
        insert(node);
        return node.val;
    }
    
    public void set(int key, int value) {
        if (map.containsKey(key)) {
            get(key);
            map.get(key).val = value;
            return;
        }
        if (cur_size < capacity) {
            cur_size ++;
        } else {
            map.remove(start.next.key);
            start.next = start.next.next;
            start.next.pre = start;
        }
        ListNode node = new ListNode(value);
        node.key = key;
        map.put(key, node);
        insert(node);
    }
    
    private void delete(ListNode node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }
    
    private void insert(ListNode node) {
        end.pre.next = node;
        node.pre = end.pre;
        node.next = end;
        end.pre = node;
    }
    
    class ListNode {
        int val;
        int key;
        ListNode pre;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
    }
}

 

[LeetCode]LRU Cache

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5014913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!