Leetcode 146 148 155
阿新 • • 發佈:2021-01-24
技術標籤:leetcode
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();
*/