day42(12.23)——leetcode面试经典150

86. 分隔链表

86. 分隔链表

咱也是成功发现leetcode的bug了哈哈哈

题目:

题解:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        //小于x的链表
        ListNode xy  = new ListNode();
        //大于等于x的链表
        ListNode dy = new ListNode();
        //当前辅助小于x的链表
        ListNode curXy = xy;
        //当前辅助大于等于的链表
        ListNode curDy = dy;
        //当前辅助遍历head的结点
        ListNode cur = head;
        while(cur != null) {
            if(cur.val < x) {
                curXy.next = cur;
                curXy = curXy.next;
            }
            else {
                curDy.next = cur;
                curDy = curDy.next;
            }
            cur = cur.next;
        }
        curDy.next = null;
        curXy.next = dy.next;
        return xy.next;
    }
}

146. LRU 缓存

146. LRU缓存

真没想到java官方还有这样的方法,牛皮

题目:

题解:

java 复制代码
import java.util.LinkedHashMap;
import java.util.Map;

class LRUCache extends LinkedHashMap<Integer, Integer> {
    private final int capacity;

    public LRUCache(int capacity) {
        // true 表示按访问顺序排序(LRU 关键!)
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        return super.getOrDefault(key, -1);
    }

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

    // 当 size() > capacity 时,自动移除最老的 entry
    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }
}
相关推荐
闪电悠米9 分钟前
力扣hot100-54.螺旋矩阵-模拟边界控制详解
算法·leetcode·矩阵
变量未定义~17 分钟前
虚拟节点-星石传送阵(4星)、强连通分量
数据结构·算法
IT方大同36 分钟前
C语言分支与循环语句
c语言·开发语言·算法
黄敬峰38 分钟前
React 待办事项 Todos 从零到一:组件化思维、状态管理与父子通信一次讲透
面试
待磨的钝刨1 小时前
深入理解主成分分析(PCA)
人工智能·线性代数·算法·机器学习
FogLetter1 小时前
嘘!WebSocket正在“偷听”你的网络请求——全双工通信的魔法
前端·面试
程序员爱钓鱼2 小时前
Rust HashMap 详解:键值存储、查询、更新与统计
后端·面试·rust
geovindu2 小时前
java: Backtracking Algorithm
java·开发语言·windows·后端·算法·回溯算法
晚风叙码3 小时前
C++ vector底层模拟实现与迭代器失效深度剖析
c++·算法