码迷,mamicode.com
首页 > 编程语言 > 详细

[持久更新] 剑指offer题目Python做题记录

时间:2018-07-08 12:34:34      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:span   rom   closed   while   app   结果   题记   const   gif   

第一题

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

  思路:先快速定位到该数在哪一行,然后再迅速定位具体位置。

技术分享图片
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        row = 0
        col = len(array[0]) - 1 
        while col >= 0 and row < len(array):
            if target == array[row][col]:
                return True
            elif target > array[row][col]:
                row = row + 1
            else:
                col = col - 1
        return False
第一题

第二题

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

  思路:使用字符串的replace方法即可。

技术分享图片
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = s.replace( ,%20)
        return s
第二题

第三题

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

  思路:先用append方法讲链表储存,然后使用reverse方法颠倒列表。

技术分享图片
# -*- 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
        out = []
        while listNode:
            out.append(listNode.val)
            listNode = listNode.next
        out.reverse()
        return out
第三题

第四题

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

  思路:前序遍历是由根开始,从左树到右数遍历。中序遍历是由左树开始,到根节点然后到右树。后序与中序相反。只考虑前序和中序,根节点在前序的首位,在中序的左树与右树的分割点。通过index方法,可以得出左树与右树的长度,然后通过递归重建二叉树。

技术分享图片
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre) == 0:
            return None
        elif len(pre) == 1:
            return TreeNode(pre[0])
        else:
            tree = TreeNode(pre[0])
            tree.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
            tree.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
        return tree
第四题

 

[持久更新] 剑指offer题目Python做题记录

标签:span   rom   closed   while   app   结果   题记   const   gif   

原文地址:https://www.cnblogs.com/zk71124720/p/9279561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!