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 和 两个节点,找到这两个节点的最低的共同父节点
class 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
leetcode 119 pascal's triangle II
就是杨辉三角,给定某一行,然后输出这一行的所有的数。
用组合 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