剑指Offer_刷题Day1

剑指Offer_刷题Day1

今天开始刷一刷剑指Offer,大概30分钟左右,写了4道题。记录下刷题日程吧,也算是对自己的生活有个交代。

从读研究生以来,一直都不太开心,感觉做的不是自己想做的事情。所以也算是寄情于物吧,希望能变得更好吧。

Q1:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

思路

  • 从右上角开始比较,不断缩进行或者列,直至左下角

Code

python

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        n1,n2=len(array),len(array[0])
        ind1,ind2=0,n2-1
        while ind1<n1 and ind2>=0:
            if target==array[ind1][ind2]:
                return True
            elif target>array[ind1][ind2]:
                ind1+=1
            else:
                ind2-=1
        return False

Q2:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路

  • 遍历比较即可

Code

python

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        news=""
        for i in s:
            if i==" ":
                news+="%20"
            else:
                news+=i
        return news

Q3:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路

  • 遍历,按顺序输出

Code

python

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        li=[]
        if listNode==None:
            return []
        Node=listNode
        li=[Node.val]
        while Node.next!=None:
            Node=Node.next
            li.append(Node.val)
        return li[::-1]

Q4:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路

  • 递归,根据前序及中序的排列

Code

python

class Solution:
    def reConstructBinaryTree(self, pre, tin):
        n=len(pre)
        print(pre)
        if n==0:
            return None
        elif n==1:
            Node=TreeNode(pre[0])
            return Node
        else:
            Node=TreeNode(pre[0])
            ind=tin.index(pre[0])
            #print(ind)
            Node.left=self.reConstructBinaryTree(pre[1:ind+1],tin[0:ind])
            Node.right=self.reConstructBinaryTree(pre[ind+1:],tin[ind+1:])
        return Node

猜你喜欢

转载自blog.csdn.net/weixin_43982484/article/details/89670047
今日推荐