1. 程式人生 > 其它 >程式設計實踐筆記No.13

程式設計實踐筆記No.13

技術標籤:程式設計實踐

程式設計實踐筆記No.13


寫在最前面,程式設計一直是我的短板,希望在leetcode練習中獲得進步!

參考Datawhale組隊學習中“LeetCodeTencent”

三道簡單類別的題目,涉及連結串列、遞迴等知識點。

題目一160. 相交連結串列

連結

編寫一個程式,找到兩個單鏈表相交的起始節點。

程式碼

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
# self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA, headB): if not headA or not headB: return None pa, pb = headA, headB while pa != pb: pa = pa.next if pa else headB pb = pb.next if pb else
headA return pa

連結

題目二169. 多數元素

連結

給定一個大小為 n 的陣列,找到其中的多數元素。多數元素是指在陣列中出現次數 大於 ⌊ n/2 ⌋ 的元素。
你可以假設陣列是非空的,並且給定的陣列總是存在多數元素

程式碼

暴力列舉
1 - 出現數字的集合,並按照集合統計出現次數;
2 - 判斷出現次數是否大於總數的一半,大於則返回。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = len(nums)
        a_set =
set(nums) kind = len(a_set) a_set_count = [0]*kind # 雙層for迴圈 for i in range(n): for j in range(kind): if nums[i]==list(a_set)[j]: a_set_count[j]+=1 if a_set_count[j] > n/2: return (list(a_set)[j])

在這裡插入圖片描述
怎麼只用遍歷一次,借鑑他人思路。
法一:排序中間的數

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort() #這個時間複雜度不明
        return nums[len(nums)//2]

在這裡插入圖片描述

法二:雜湊表

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 1:
            return nums[0]
        max_count=n//2
        hashmap = {}
        for num in nums:
            if num not in hashmap:
                hashmap[num] = 1
                continue
            hashmap[num] += 1
            if hashmap[num] > max_count:
                return num

法二借鑑連結
在這裡插入圖片描述

題目三206. 反轉連結串列

連結

反轉一個單鏈表。

程式碼

雙指標

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = pre

            pre = cur
            cur = tmp
        return pre

在這裡插入圖片描述

連結