146.LRU缓存机制
题目描述:运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
思路:利用字典存储关键字和它的值,但字典没有顺序,无法决定最少使用的关键字,因此再用一个列表来存储关键字key。
代码如下:
public class LRUCache {
private readonly List<int> lst;
private readonly Dictionary<int,int> dic;
public LRUCache(int capacity) {
lst=new List<int>(capacity);
dic=new Dictionary<int,int>(capacity);
}
public int Get(int key) {
if(lst.Contains(key))
{
lst.Remove(key);
lst.Add(key);
return dic[key];
}
return -1;
}
public void Put(int key, int value) {
if(lst.Contains(key))
{
lst.Remove(key);
dic.Remove(key);
}
else if(lst.Count==lst.Capacity)
{
dic.Remove(lst[0]);
lst.RemoveAt(0);
}
lst.Add(key);
dic.Add(key,value);
}
}
/**
* 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);
*/
148.排序链表
题目描述:
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
思路:利用并归排序。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode SortList(ListNode head)
{
if (head == null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head;
ListNode dv = null;
while (p2 != null&&p2.next!=null)
{
dv = p1;
p1 = p1.next;
p2 = p2.next.next;
}
dv.next=null;
ListNode l1 = SortList(head);
ListNode l2 = SortList(p1);
return Merge(l1, l2);
}
private ListNode Merge(ListNode p1,ListNode p2)
{
ListNode phead = new ListNode();
ListNode temp = phead;
while (p1 != null && p2 != null)
{
if (p1.val > p2.val)
{
temp.next = p2;
p2 = p2.next;
}
else
{
temp.next = p1;
p1 = p1.next;
}
temp = temp.next;
}
if (p1 == null)
temp.next = p2;
else if (p2 == null)
temp.next = p1;
return phead.next;
}
}
155.最小栈
题目描述:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
思路:利用列表存储即可。
代码如下:
public class MinStack
{
private List<int> _lst;
/** initialize your data structure here. */
public MinStack()
{
_lst = new List<int>();
}
public void Push(int x)
{
_lst.Add(x);
}
public void Pop()
{
_lst.RemoveAt(_lst.Count-1);
}
public int Top()
{
return _lst[_lst.Count-1];
}
public int GetMin()
{
return _lst.Min();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.Push(x);
* obj.Pop();
* int param_3 = obj.Top();
* int param_4 = obj.GetMin();
*/