力扣剑指Offer-简单-III

# =========18 删除链表的节点=====================================================
class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        if head.val == val: 
            return head.next
        pre, cur = head, head.next
        while cur and cur.val != val:
            pre, cur = cur, cur.next
        if cur:
            pre.next = cur.next
        return head
# =============================================================================
# ========55-II平衡二叉树========================================================
'''
如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
''' 
class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if not root: #if root == None 是否可行呢?
            return True
        if (abs(self.height(root.left) - self.height(root.right)) > 1):
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)
    def height(self,root):
        if not root: 
            return 0
        return 1+max(self.height(root.left),self.height(root.right))
    
#这是我看着答案写出来的,但是网页上说输出的不是int

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if not root:
            return True
        if (abs(self.height(root.left) - self.height(root.right)) > 1):
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)

    def height(self,root):
        if not root:
            return 0
        return 1 + max(self.height(root.left) , self.height(root.right))
    
'''
这道题的思路:
    1.先定义一个求树的深度的函数。(函数解释:如果是根节点返回0,否则返回1 + (左子树深度和右子树深度的最大值))
    2.再写isBalanced函数:如果只有根节点那么返回True,如果左子树深度 - 右子树深度 > 1,那么返回False.否则进入左右节点的isBalanced递归。
'''
# =============================================================================
# ======28 对称的二叉树==========================================================
#k神写的,没有用先求出镜像函数,然后再比较的思路。
#我根据k神代码改写的,可以运行出来
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def recur(L, R):#recur递归的意思
            if not L and not R:  #如果L和R都是空的,则返回的是True
                return True
            if not L or not R or L.val != R.val: #如果L是空的或者R是空的或者L的值 = R的值,则返回False
                return False
            return recur(L.left, R.right) and recur(L.right, R.left)
        if  root: 
            return recur(root.left, root.right)
        else:
            return True
# =============================================================================
# ============40 最小的k个数====================================================
#这是我写的,但是运行错误
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        aDict = {}
        res = []
        #maxNum = max(arr)

        for i in range(len(arr)):
            aDict[arr[i]] = i
        for i in range(k):
            a = min(arr) #a是最小的数
            b = aDict[a]  #b是最小数在List中对应的编号
            res.append(arr[b])
            arr[b] = 100000   #唉我也不知道为什么这个就运行不出来
        return res

#这是答案:
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        arr.sort()  #这是从小到大排列,非常重要
        return arr[:k]
# =============================================================================
# =====53-I在排序数组中查找数字I-统计一个数字在排序数组中出现的次数。====================
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if target not in nums:
            return 0
        aDict = {}
        for i in nums:
            if i in aDict:
                aDict[i] += 1
            else:
                aDict[i] = 1
        return aDict[target]
# =============================================================================
# ================67 扑克牌中的顺子==============================================
'''
构成顺子的条件:
1.从第一个非零数起,没有重复的数字
2.sort从小到大排列后,最大数减去第一个非零数要小于5
'''

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        joker = nums.count(0)
        nums.sort() # 数组排序
        for i in range(joker,4):
            if nums[i] == nums[i + 1]:
                return False # 若有重复,提前返回 false
        if (nums[4] - nums[joker]) < 5 :# 最大牌 - 最小牌 < 5 则可构成顺子
            return True 
        else:
            return False
# =============================================================================
# ============53-II 0~n-1中确实的数字============================================
数学方法:求出这个数列的和应该是多少,减去实际的和,就正好是缺少的数字
class Solution:
    def missingNumber(self, nums):
        length = len(nums) + 1
        return (length - 1) * length // 2 - sum(nums)
# =============================================================================
# =======29 顺时针打印矩阵=======================================================
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return matrix
        res = []
        l = 0
        t = 0
        r = len(matrix[0]) - 1
        b = len(matrix) - 1
        while True:
            for i in range(l,r + 1):
                res.append(matrix[t][i])
            t += 1
            if t > b:
                break
            for i in range(t,b + 1):
                res.append(matrix[i][r])
            r -= 1
            if l > r:
                break
            for i in range(r,l - 1,-1):
                res.append(matrix[b][i])
            b -= 1
            if t > b:
                break
            for i in range(b,t - 1,-1):
                res.append(matrix[i][l])
            l += 1
            if l > r:
                break
        return res
# =============================================================================
# ==============58-I翻转单词顺序=================================================
#这道题的注意是,字符串转换成列表后要给列表重新赋值。同理列表转换成字符串的时候也一样
#答案
class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.strip() # 删除首尾空格
        strs = s.split() # 分割字符串
        strs.reverse() # 翻转单词列表
        return ' '.join(strs) # 拼接为字符串并返回
#我写的,也能跑出来
class Solution:
    def reverseWords(self, s: str) -> str:
        s_list = s.strip().split()
        res = []
        for i in range(len(s_list)):
            a = s_list.pop()
            res.append(a)
        return " ".join(res)
# =============================================================================
# ==========10-II青蛙跳台阶问题===================================================================
class Solution:
    def numWays(self, n: int) -> int:
        if n == 0:
            return 1
        if n == 1:
            return 1
        if n == 2:
            return 2
        a = 1#f(1)
        b = 2#f(2)
        res = 0#
        for i in range(n - 2):
            res = a + b
            a = b
            b = res
        return res % 1000000007  %取模
# =============================================================================
# ========10-I斐波那契数列=====================================================================
class Solution:
    def fib(self, n: int) -> int:
        a = 0
        b = 1
        res = 0
        if n == 0:
            return 0
        if n == 1:
            return 1
        for i in range(n - 1):
            res = a + b
            a = b
            b = res
        return res % 1000000007   
# =============================================================================
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十子木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值