剑指offer刷题记录|顺序刷题第一周

文章目录

    • 剑指offer 03 数组中重复的数字
    • 剑指offer 04 二维数组中的查找
    • 剑指offer 05 替换空格
    • 剑指offer 06 打印链表从尾到头
    • 剑指offer 07 根据前序和中序重建二叉树
    • 剑指offer 08 两个栈实现队列
    • 剑指offer 10-I 斐波那契数列

剑指offer 03 数组中重复的数字

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        #  用set()判断是否重复,注意set添加元素要用add
        setlist = set()
        for ele in nums:
            if ele not in setlist:
                setlist.add(ele)
            else:
                return ele

        # 排序,前后相同则为重复
        nums.sort()
        for i in range(len(nums)):
            if nums[i]==nums[i+1]:
                return nums[i]

剑指offer 04 二维数组中的查找

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        # 从右上角开始遍历,往左递减,往下递增。
        if matrix==[]: return False
        row, column = 0, len(matrix[0])-1
        while 0<=row<len(matrix) and 0<=column<len(matrix[0]):
            if matrix[row][column]>target:
                column -= 1
            elif matrix[row][column]==target:
                return True
            else:
                row += 1
        return False

剑指offer 05 替换空格

class Solution:
    def replaceSpace(self, s: str) -> str:
        # 正常操作
        res = ''
        for ele in s:
            if ele == ' ':
                res+='%20'
            else:
                res+=ele
        return res

        # 使用python的api replace
        return s.replace(' ','%20')

        # 字符串按空格分开,然后用%20拼接
        res = s.split(' ')
        return '%20'.join(res)

剑指offer 06 打印链表从尾到头

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        # 法一:python转换只需要[::-1]
        res = []
        while head:
            res.append(head.val)
            head = head.next
        return res[::-1]
        # 法二:堆栈可以先入后出,解决链表只能从头到尾的问题
        res = list()
        result = []
        while head:
            res.append(head.val)
            head = head.next
        while res:
            result.append(res.pop())
        return result

剑指offer 07 根据前序和中序重建二叉树

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        # 想法:分治。前序遍历的第一个是root,建立节点root = TreeNode(preorder[0])。
        # root在中序的index,左边是左子树,右边是右子树。
        # preorder前序遍历(根,左,右):root, pre_left -- pre_right, pre_left -- pre_right
        # inorder中序遍历(左,根,右: in_left -- in_right' ,idx, in_left' in_right
        # 左树长度:idx-in_left
        def rebuild(pre_left, pre_right, in_left, in_right):
            if in_left>in_right:
                return
            root = pre_left
            node = TreeNode(preorder[root])
            idx = dic[node.val]
            node.left = rebuild(root+1, root+idx-in_left, in_left, idx-1)
            node.right = rebuild(root+idx+1-in_left, pre_right, idx+1, in_right)
            return node # 忘记了可就是null了
        if not preorder: return
        res = []
        dic = {
     }
        for i in range(len(inorder)):
            dic[inorder[i]] = i
        return rebuild(0, len(inorder)-1, 0, len(inorder)-1 )

剑指offer 08 两个栈实现队列

class CQueue:

    def __init__(self):
        self.res = []

    def appendTail(self, value: int) -> None:
        # 添加元素
        self.res.append(value)
        return self.res

    def deleteHead(self) -> int:
        # 删除第一个元素,注意不是堆栈啦,所以不要用pop()
        if self.res == []:
            return -1       
        value = self.res[0]
        self.res = self.res[1:]
        return value

剑指offer 10-I 斐波那契数列

class Solution:
    def fib(self, n: int) -> int:
        # 法1: 设置一个list, 不断添加
        if n == 0: return 0
        if n == 1: return 1
        res = [0, 1]
        for i in range(2,n+1):
            tmp = res[i-1]+res[i-2]
            res.append(tmp)
        return res[-1] % 1000000007 # 防止int32溢出,取模

        # 法2: 用python的替代法
        a, b = 0, 1
        for i in range(n):
            a, b = b, a+b
        return a % 1000000007

你可能感兴趣的:(刷题笔记)