leetcode amazon 面试题(三)

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


21. Merge Two Sorted Lis

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值