leetcode amazon 面試題(三)
阿新 • • 發佈:2019-01-02
leetcode 21. merge two sorted lists
大概的意思就是 給兩個list, 然後把它們按照所有元素的 從小到大的順序排序。
這裡分享一個比較簡潔的寫法:
class Solution(object): def mergeTwoLists(self, l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next
遇到連結串列的題目 首先要注意頭結點的問題。一般都是直接建一個頭結點,然後直接用用 dummy.next 這樣比較方便。
leetcode 235 lowest common ancestor of a binary search tree
給一個bst 和 兩個節點,找到這兩個節點的最低的共同父節點
leetcode 119 pascal's triangle IIclass Solution(object): def lowestCommonAncestor(self, root, p, q): while root: if (p.val < root.val and q.val < root.val): root = root.left elif (p.val > root.val and q.val > root.val): root = root.right else: return root
就是楊輝三角,給定某一行,然後輸出這一行的所有的數。
用組合 Cki 就解決了。
class Solution(object): def cal(self, index, rowIndex): sum = 1 for i in range(0, index): sum = sum * (rowIndex - i) / (i+1) return sum def getRow(self, rowIndex): res = [] for i in range(0, rowIndex): res.append(self.cal(i, rowIndex)) res.append(1) return res