Posts

[LeetCode] #78. Subsets

題目 Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. 直覺解 構想: 用 nums 的長度為遞迴分層 base case: nums 長度 1。只有一個元素的話,所有可能的 subset 就是[有那個元素]、[沒有那個元素] inductive case: pop nums 的最後一個元素,因此 nums 長度會 -1。用遞迴算出 nums 長度-1 的所有 subset,迭代這些 subset,每一圈都把底下這兩個東西 append 到答案裡: 這個 subset 有 pop 掉的最後一個元素 這個 subset 沒有 pop 掉的最後一個元素 python 3 實作: def subsets(self, nums: List[int]) -> List[List[int]]:     if len(nums) == 1:         ireturn [[], [nums[0]]]     result = []     last_item = nums.pop()     prev_result = self.subsets(nums)     for item in prev_result:         icopy = item.copy()         iitem.append(last_item)         iresult.append(copy)    ...

[LeetCode] #454. 4Sum II

題目 Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 直覺解 構想一(失敗): 用 for 回圈把所有組合都嘗試一次 python 3 實作: def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:     count = 0         for i in nums1:             for j in nums2:                 for k in nums3:                     for l in nums4:                         if i +j + k + l == 0:                             count += 1     return count 錯誤:Time Limit Exceeded input: nums1 = [-8,-7,-14,-5,5,-24,-16,-24,-23,6,3,-26,-10,-1...

[LeetCode] #100. Same Tree

題目 Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. 直覺解 構想一: 參考 94. Binary Tree Inorder Traversal ,用 Inorder 的方式,遍歷整棵樹,並檢查每個節點的值是否相同 python 3 實作: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:     stack_p = []     stack_q = []     while stack_p or stack_q or p or q:         if len(stack_p) != len(stack_q):             return False         if (not p and q) or (p and not q):             return False         if p or q:             stack_p.append(p)             stack_q.append(q)             p = p.left             q = ...

[LeetCode] #725. Split Linked List in Parts

題目 Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts". The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null. The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later. Return a List of ListNode's representing the linked list parts that are formed. Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ] 直覺解 構想: 先計算整個 list 有多長,分成「list 長度 < k」和「list 長度 >= k」兩種狀況處理。 若 list 長度 < k,則每個 part 只有一個節點,剩下的位置就用 null 補滿。 若 list 長度 >= k,則計算每個 part 有多長,最後根據每個 part 的長度去分割 list。 javascript 實作: const splitListToParts = function(root, k) {     const result = []     let current = root     let prevNode     let length = 0  ...

[Udemy] Python 3: Deep Dive 系列課程備忘錄

Part 1 - Functional Section 6 影片編號:85 dir([object]):查詢物件屬性 inspect module 影片編號:90、91 functools.reduce(function, iterable[, initializer]) min(iterable), max(iterable), sum(iterable), any(iterable), all(iterable) 把遞迴改寫成 reduce:程式碼在影片 #91 時間 18:29 處 影片編號:92 functools.partial(func, /, *args, **keywords) 回傳某些參數已經被固定了的 func 可能的坑:呼叫「某些參數已經被固定了的 func」時,仍可以覆寫被固定住的參數值 def power(base, exponent):     return base ** exponent     square = partial(power, exponent=2)     print(square(5, exponent=3)) 影片編號:93 partial 可能的應用場合: sorted(iterable, *, key=None, reverse=False)、list.sort(*, key=None, reverse=False) 的 key 只能放一個參數的函式 影片編號:94 operator module :getitem(a, b)、 itemgetter(item)、attrgetter(attr) Section 7 影片編號:97 宣告 global 變數 when python encounters a function definition at compilt-time when function is...

[LeetCode] #225. Implement Stack using Queues

題目 Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means only push to back , peek/pop from front , size , and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue's standard operations. 直覺解 構想: 用 list 模擬 queue。 使用兩個 queue,q1 和 q2。q1 用來存資料,q2 是要取出資料時,用來暫放資料的:要拿出 stack 中的東西時,先把 q1 的資料一個一個搬進 q2 裡,直到 q1 裡只剩下一個東西時,剩下的那個就是要 return 的東西。 python ...

[LeetCode] #347. Top K Frequent Elements

題目 Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 1 <= nums.length <= 10 5 k is in the range [1, the number of unique elements in the array] . It is guaranteed that the answer is unique. 直覺解 構想: 紀錄每個數字出現幾次,依照出現次數由大至小排序,取出前 k 個數字。 javascript 實作: const topKFrequent = function(nums, k) {     if (nums.length === k) { return nums }     let numsDisplayCount = {}     const result = []     for (const num of nums) {         if (!numsDisplayCount[num]) {                 numsDisplayCount[num] = 1         } else {                 numsDisplayCount[num]++         }     }     numsDisplayCount = Object.entries(numsDisplayCount).sort((a, b) => b[1] - a[1])     for (let i = 0; i ...