Leetcode习题合并两个有序数组,格雷编码等

合并两个有序数组

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        p1,p2=m-1,n-1 #倒指针
        p=m+n-1 
        while p1 >= 0 and p2 >= 0:
            if nums1[p1]<nums2[p2]:
                nums1[p]=nums2[p2]
                p2-=1
            else:
                nums1[p]=nums1[p1]
                p1-=1

            p-=1

格雷编码

class Solution:
    def grayCode(self, n: int) -> List[int]:
        res=[0] #c初始化G(0)
        head=1 #初始化位数标识

        for i in range(n): #外层循环总位数n
            for j in range(len(res)-1,-1,-1): #内循环倒叙遍历res
                res.append(head+res[j]) #位数标识+当前索引对应的值
            head<<=1 #x<<1是将x的二进制表示左移一位,相当于原数x乘2,例如4→8;<<=,就是对变量进行位运算移位之后的结果再赋值给原来的变量,类似+=

        return res

二叉树的最大深度

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        else:
            left_height=self.maxDepth(root.left)
            right_height=self.maxDepth(root.right)

            return max(left_height,right_height)+1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值