前言
今天是寒假LeetCode刷题打卡的第十二天,继续坚持、继续加油!也希望我的博文能够帮助到大家,若有疑问,可以随时私信Call我!
一、146. LRU 缓存机制
1. 题目描述
难度:中等
2. 代码实现
class LRUCache extends LinkedHashMap<Integer, Integer>{
private int capacity;
public LRUCache(int capacity) {
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);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
二、148. 排序链表
1. 题目描述
难度:简单
2. 代码实现
class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode slow = head; //慢指针
ListNode fast = head.next; //快指针
while(fast!=null && fast.next!=null){ //快慢指针找到链表中点
slow = slow.next; //慢指针走一步
fast = fast.next.next; //快指针走两步
}
ListNode rightHead = slow.next; //链表第二部分的头节点
slow.next = null; //cut 链表
ListNode left = sortList(head); //递归排序前一段链表
ListNode right = sortList(rightHead); //递归排序后一段链表
return merge(left,right);
}
public ListNode merge(ListNode h1,ListNode h2){ //合并两个有序链表
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
while(h1!=null && h2!=null){
if(h1.val < h2.val){
p.next = h1;
h1 = h1.next;
}else{
p.next = h2;
h2 = h2.next;
}
p = p.next;
}
if(h1!=null) p.next = h1;
else if(h2!=null) p.next = h2;
return dummy.next;
}
}
三、155. 最小栈
1. 题目描述
题号:142
难度:中等
155. 最小栈-leetcode官网
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
进阶:
你是否可以不用额外空间解决此题?
3. 代码实现
class MinStack {
private ListNode top;
private min_stack min_Stack=null;
public MinStack() {
top=new ListNode();
min_Stack=new min_stack();
}
public void push(int x) {
ListNode newNode=new ListNode(x);
newNode.next=top.next;
top.next=newNode;
min_Stack.push(x<min_Stack.top()?x:min_Stack.top());
}
public void pop() {
if(top.next!=null)
{
ListNode Del=top.next;
top.next=Del.next;
min_Stack.pop();
Del=null;
}
}
public int top() {
if(top.next!=null)
return top.next.val;
return Integer.MAX_VALUE;
}
public int getMin() {
return min_Stack.top();
}
}
class min_stack
{
private ListNode top;
public min_stack() {
top=new ListNode();
}
public void push(int x) {
ListNode newNode=new ListNode(x);
newNode.next=top.next;
top.next=newNode;
}
public void pop() {
if(top.next!=null)
{
ListNode Del=top.next;
top.next=Del.next;
Del=null;
}
}
public int top() {
if(top.next!=null)
return top.next.val;
return Integer.MAX_VALUE;
}
}
class ListNode
{
int val;
ListNode next;
ListNode(){this.next=null;}
ListNode(int val)
{
this.val=val;
this.next=null;
}
ListNode(int val,ListNode next)
{
this.val=val;
this.next=next;
}
}
总结
以上就是今天 LeetCode寒假刷题 Day12 所做的三道题。若有任何疑问,欢迎私信或评论区留言鸭!