算法打卡:第8周

问题一

LRU 缓存:https://leetcode-cn.com/problems/lru-cache-lcci/

思路:首先需要理解LRU的含义:LRU-最近最久未使用; LFU-最近最少使用(最不常用)。很显然,因为需要存储K-V键值,所以需要使用到HashMap结构。其次,需要维护一个结构,来存储最近使用的到的数据的key,以便在容量满了的时候去除最近最久未使用的那个key。

class LRUCache {
    private Map<Integer, Integer> cache;
    private List<Integer> deque;
    private int capaticy;

    public LRUCache(int capacity) {
        cache = new HashMap<>(capacity);
        deque = new LinkedList<>();
        this.capaticy = capacity;
    }

    public int get(int key) {
        Integer val = cache.get(key);
        if (val == null) {
            val = -1;
        } else {
            deque.remove(Integer.valueOf(key));
            deque.add(Integer.valueOf(key));
        }
        return val;
    }

    public void put(int key, int value) {
        this.remove(key);
        if (cache.size() >= capaticy) {
            Integer removeKey = deque.remove(0);
            cache.remove(removeKey);
        }
        cache.put(key, value);
        deque.add(Integer.valueOf(key));
    }

    private boolean remove(int key) {
        if (cache.containsKey(key)) {
            cache.remove(key);
            deque.remove(Integer.valueOf(key));
            return true;
        }
        return false;
    }
}

问题二

二叉树的最近公共祖先:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/

思路:递归寻找指定节点的父节点,并将所有的父节点依次存储起来。然后再去寻找共同父节点中深度最大的那一个。

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    List<TreeNode> pParentList = new LinkedList<>();
    List<TreeNode> qParentList = new LinkedList<>();
    this.findNode(root, p, pParentList);
    this.findNode(root, q, qParentList);
    TreeNode sameParentNode = root;
    // 找到深度最大的公共父节点
    for (int i = pParentList.size() - 1, j = qParentList.size() - 1; i >= 0 && j >= 0; i--, j--) {
        if (pParentList.get(i).val == qParentList.get(j).val) {
            sameParentNode = pParentList.get(i);
        }
    }
    return sameParentNode;
}

// 寻找目标node的所有父节点
private boolean findNode(TreeNode root, TreeNode target, List<TreeNode> nodeList) {
    if (root.val == target.val) {
        nodeList.add(root);
        return true;
    }
    if (root.left != null && this.findNode(root.left, target, nodeList)) {
        nodeList.add(root);
        return true;
    }
    if (root.right != null && this.findNode(root.right, target, nodeList)) {
        nodeList.add(root);
        return true;
    }
    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值