link: https://leetcode.com/problems/linked-list-cycle/
用set紀錄看過的node,如果有重複就代表有cycle。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
visit = set()
while head is not None:
if head in visit:
return True
visit.add(head)
head = head.next
return False
Floyd Cycle Detection Algorithm (龜兔賽跑演算法),用一快一慢的兩個指標,如果快的指標會追到慢的指標,就代表有cycle。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
leetcode
link: https://leetcode.com/problems/
Feb 9, 2024Difficulty: Medium link: https://leetcode.com/problems/distribute-coins-in-binary-tree/ 1. DFS $O(N)$ runtime, $O(H)$ space 定義dfs函數,計算以node為root的subtree,扣掉每個child node需要的1枚硬幣後,總共會多(或少)幾枚硬幣。 如果硬幣有多,回傳值就是正的;如果硬幣有缺,回傳值就是負的;剛剛好不多不缺的情況,回傳值為0。 dfs函數顯示,node最少還需要幾枚硬幣(缺硬幣的情況),或著node至少要給出幾枚硬幣(多硬幣的情況),才能達成題目要求的硬幣分布。
Nov 26, 2022Difficulty: Medium link: https://leetcode.com/problems/permutations/ 1. Backtracking $O(n!)$ runtime, $O(n)$ space 需要列出所有排列數,可以用backtracking。用take紀錄有沒有拿過nums的第i個元素。 python class Solution: def permute(self, nums: List[int]) -> List[List[int]]:
Nov 26, 2022Difficulty: Medium link: https://leetcode.com/problems/permutations-ii/ 1. Backtracking $O(n!)$ runtime, $O(n)$ space 用Counter記錄每個數字出現了幾次,在排列時同個數字就會當成同一類。 python class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]:
Nov 26, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up