You can find solutions of Leetcode problems online. Sometimes my own solutions are more intuitive to me. Here I present my solutions that I find interesting in Python3 and my notes.
In solving a problem, the very first step is to write test cases that cover the whole problem domain (aka Test-driven development). This forces you think more about the problem and understand it thoroughly.
121. Best Time to Buy and Sell Stock:
def maxProfit(self, prices: List[int]) -> int: maxProfit = 0 iLowestPrice = 0 #runtime is O(n) because there is only one for loop for j in range(iLowestPrice + 1, len(prices)): profit = prices[j] - prices[iLowestPrice] if profit > maxProfit: maxProfit = profit if prices[j] < prices[iLowestPrice]: iLowestPrice = j return maxProfit
141. Linked List Cycle: To check if a node object already exists, using a set (hash set) instead of a list is much faster, in fact 66 times faster for this particular problem. This is due to comparing the hash-based key when using a set instead of comparing all fields of objects when using a list.
104. Maximum Depth of Binary Tree: My inefficient Python solution runtime (105 ms) was 26 times slower than my similar C++ solution (4 ms). For testing purposes, I wrote a function to create a binary tree from a list:
def toBSTree(aList): nodes = [] for n in aList: nodes.append(TreeNode(n)) for i in range((len(aList)-2) // 2 + 1): left = nodes[2*i+1] right = nodes[2*i+2] if left.val is not None: nodes[i].left = left if right.val is not None: nodes[i].right = right return nodes[0]
- adjacencyList[node] = neighbor nodes of each node
- isVisited[node] = was this node visited before
def printBSTreeRecursive(root): if root is None: return print(root.val) printBSTreeRecursive(root.left) printBSTreeRecursive(root.right) def printBSTreeIterative(root): stack = [root] while stack: node = stack.pop() print(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left)01.03.2023: My Leetcode replit repo. Binary search tree keys have to be unique.
No comments:
Post a Comment