【刷題】 重難點備忘錄

目錄

各種操作

鏈表反轉:

數據結構

OrderedDict 有序字典(哈希表 + 雙向鏈表)

PriorityQueue 部分排序


 

各種操作

鏈表反轉:

206. 反轉鏈表

#怎麼突然報錯了 哦 while(head) 應該是head1 可是 這倆變量不應該一樣嗎 #不一樣! head還剩1 head1是空#怎麼突然報錯了
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#原地逆置 頭插法
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        rev=None
        head1=copy.deepcopy(head) # 直接修改head會破壞鏈表結構  這樣修改也會的 #而你自己寫的頭插法 是不會修改head的
        while(head1):
            #第一次head就斷開了
#             print_list('head',head)
#             print_list('head1',head1)
            rev,rev.next,head1=head1,rev,head1.next   #因爲rev=head1?還是因爲你的頭插法是用val新建node 不是直接賦值 可是那樣空間複雜度更大? 
            #上面head1=copy.deepcopy(head) 就不會修改原鏈表了 因爲先把head賦值給rev 又rev.next=None 所以head只剩第一個元素

        # print_list('rev',rev)
        # print_list('head',head)
        # print_list('head1',head1)
        return rev

#鏈表輸出
def print_list(s,head):
    print(s,end=" ")
    while(head):
        print(head.val,end=' ')
        head=head.next
    print()

234. 迴文鏈表

#cleaned11 45 -> 
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#翻轉前一半 對比
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        slow,fast=head,head 
        rev=None
        
        while(fast and fast.next):
            fast=fast.next.next 
            rev, rev.next, slow = slow, rev, slow.next 
        
        if fast:
            slow = slow.next
            
        while(slow and slow.val==rev.val):
            slow,rev=slow.next,rev.next
        return not slow
        

 

數據結構

OrderedDict 有序字典(哈希表 + 雙向鏈表)

146. LRU緩存機制

class LRUCache(OrderedDict):

    def __init__(self, capacity: int):
        self.capacity=capacity

    def get(self, key: int) -> int:
        if key in self:
            self.move_to_end(key)
            return self[key]
        else:
            return -1

    def put(self, key: int, value: int) -> None:
        if key in self:
            self.move_to_end(key) #已經在字典裏了 就移到最後
        self[key]=value #因爲可能key已經有了 但是value的值是新的 即改寫
#         else:
#             self[key]=value #重寫不會改變順序 但這樣寫清楚 不對 放在else裏就錯了 why
        if len(self)>self.capacity:
            self.popitem(last=False)


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

PriorityQueue 部分排序

LeetCode 中的 PriorityQueue 總結:https://www.dazhuanlan.com/2019/12/06/5de9e52da6794/

面試題40. 最小的k個數

from queue import PriorityQueue
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        if not arr or not k: return []
        n=len(arr)
        pq=PriorityQueue()
        for i in arr:
#             print(pq.queue)
            pq.put((-i,i))
            if pq.qsize()>k: #超出後 彈出最小的
                pq.get()
            
#         print(pq.queue)
        
        re=[] #[1,2] 或者 [2,1] 輸出逆序也可以
        while not pq.empty(): #不能直接pq來判斷空 否則會死循環
            re.append(pq.get()[1]) #雖然pq.queue是無序 但是出隊時是有序 怎麼看有序的列表呢
        return re        
        
# Solution().getLeastNumbers( [3,2,1],
# 2 )

347. 前 K 個高頻元素

#80 29 哇 和用heapq一模一樣 heapq的複雜度 到底是知乎裏說的logn 還是leetcode題解裏的logk 但是明明python庫裏寫了是和sorted(...)[:k]一樣 那應該就是logn 可是爲啥提交 時間一樣
#用pq
from queue import PriorityQueue
from collections import Counter
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        counter=Counter(nums)
#         print(counter)
#         print(dict(counter))

        pq=PriorityQueue()
        for key,freq in counter.items():
#             print(pq.queue)
            if len(pq.queue)<k: #把複雜度優化到nlogk 如果k接近n的話 可以反過來 保存n-k個頻率小的數 
                pq.put((freq,key))   
            elif freq>pq.queue[0][0]: #只保存freq最大的k個數哦
                head=pq.get()
#                 print('head',head)
                pq.put((freq,key))   
                
        return [e[1] for e in pq.queue] #取出key
    

# Solution().topKFrequent(  [1,1,1,2,2,3,4,4,4] ,2)

239. 滑動窗口最大值

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章