lc146 146. LRU Cache

https://leetcode-cn.com/problems/lru-cache/

[brainstorm]
1 map structure for key, value pair.
2 remove least recent used, meaning earliest element, use list.
list keep item order.
3 while update/visit element, timestamp change. what we should do?
remove the corresponding item.
however, cannot locate which item, need to scan whole list.
4 to locate item, need structure for item index. can we do that?

[in summary] 3 structure
basic map for key, value pair
list for item order
structure for item index.

5 Three structure should be consistent.

[bug code]

class LRUCache {

    Map<Integer, Integer> map;
    List<Integer> list;
    Map<Integer, Integer> indexes;
    int cap;
    int cnt=0;
    public LRUCache(int capacity) {

        map = new HashMap<>();
        list = new ArrayList<>();
        indexes = new HashMap<>();
        this.cap = capacity;
    }
    
    public int get(int key) {
        
        if(!map.containsKey(key)){
            return -1;
        }
        list.remove(indexes.get(key));
        list.add(key);
        indexes.put(key, list.size()-1);
        return map.get(key);
    }
    
    public void put(int key, int value) {

        //not contain key
        if(!map.containsKey(key)){
            if(cnt==cap){
                int k = list.get(0);
                list.remove(0);
                map.remove(k);
                indexes.remove(k);
                cnt--;                
            }            
            map.put(key, value);
            list.add(key);
            indexes.put(key, list.size()-1);
            cnt++;
        }

        //contain key
        map.put(key, value);
        list.remove(indexes.get(key));
        list.add(key);
        indexes.put(key, list.size()-1);
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值