leetcode-4.21[169. 多數元素、160. 相交鏈表、155. 最小棧](python解法)

題目1

在這裏插入圖片描述

題解1

from queue import PriorityQueue
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        pq = PriorityQueue(maxsize=0)
        for num in set(nums):
            pq.put((-nums.count(num), num))
        
        return pq.get()[1]

題目2

在這裏插入圖片描述

題解2

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if headA is None or headB is None:
            return None
        a, b = headA, headB
        while a != b:
            a = a.next if a else headB
            b = b.next if b else headA
        return a

題目3

在這裏插入圖片描述

題解3

# 列表實現
class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.container = []

    def push(self, x: int) -> None:
        self.container.append(x)

    def pop(self) -> None:
        self.container.pop()

    def top(self) -> int:
        return self.container[-1]

    def getMin(self) -> int:
        return min(self.container)


# 鏈表實現
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None


class MinStack:
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.val = None
        self.next = None
    
    def push(self, x: int) -> None:
        p = Node(x)
        p.next = self.next
        self.next = p

    def pop(self) -> None:
        if self.next:
            self.next = self.next.next

    def top(self) -> int:
        if self.next:
            return self.next.val
        return None

    def getMin(self) -> int:
        # 設第一個節點的值爲最小值,一直往後比較
        p = self.next
        minnum = p.val
        while p != None:
            minnum = min(minnum, p.val)
            p = p.next
        return minnum
    

# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

附上題目鏈接:

題目1鏈接
題目2鏈接
題目3鏈接

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