剑指offer之python篇(一)

001 二维数组的查找

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

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        col=len(array[0])
        raw=len(array)
        i=0
        j=col-1
        while (i<raw and j>=0):
            if array[i][j]> target:
                j=j-1
            elif array[i][j]< target:
                i=i+1
            else:
                return True
        return False

002 替换空格

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

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        slit=s.split(" ")
        return '%20'.join(slit)

003从尾到头打印链表

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

# -*- 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
        list=[]
        while listNode:
            list.append(listNode.val)
            listNode=listNode.next
        return list[::-1]
        

004 重建二叉树

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

# -*- 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 not pre or not tin:
            return None
        if len(pre) != len(tin):
            return None
        root=pre[0]
        rootnode=TreeNode(root)
        pos=tin.index(root)

        lefttin=tin[:pos]
        leftpre=pre[1:pos+1]
        
        rightpre=pre[pos+1:]
        righttin=tin[pos+1:]
        
        left=self.reConstructBinaryTree(leftpre,lefttin)
        rootnode.left=left
        
        right=self.reConstructBinaryTree(rightpre,righttin)
        rootnode.right=right
            
        return rootnode

005 用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.acceptStack=[]
        self.outputStack=[]
        
    def push(self, node):
        self.acceptStack.append(node)
        # write code here
    def pop(self):
        if self.outputStack ==[] :
            while self.acceptStack :
                self.outputStack.append(self.acceptStack.pop())
        if self.outputStack !=[] :
            return self.outputStack.pop()

006旋转数组的最小数字

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, arr):
        
        if 0 == len(arr):
            return 0
        low = 0
        high = len(arr)-1
        while high - low > 1:
            middle = (low+high)//2
            if arr[middle] == arr[low] and arr[low] == arr[high]:
                for i in range(low+1, high+1):
                    if arr[i] < arr[low]:
                        return arr[i]
            elif arr[middle] >= arr[low]:
                low = middle
            elif arr[middle] <= arr[high]:
                high = middle
        return arr[high]

007 斐波那契数列

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        if n==0:
            return 0
        else :
            res=[0,1]
            for i in range(2,n+1):
                res.append(res[i-1]+res[i-2])
            return res[-1]

008 跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

# -*- coding:utf-8 -*-
class Solution:
    def jumpFloor(self, number):
        # write code here
        if number<1:
            return 0
        if number<=2:
            return number
        ret=0
        a=1
        b=2
        for i in range(3,number+1):
            ret=a+b
            a=b
            b=ret
        return ret

009 变态跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

class Solution:
    def jumpFloorII(self, number):
        # write code here
        return pow(2,number-1)

010 矩形覆盖

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

# -*- coding:utf-8 -*-
class Solution:
    def rectCover(self, number):
        # write code here
        if number ==0:
            return 0
        if number ==1:
            return 1
        a=1
        b=2
        for i in range(3,number+1):
            b=a+b
            a=b-a
        return b

011 二进制中1的个数

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        count=0
        if n<0:
            n=n& 0xffffffff
        while n:
            count=count+1
            n=n&(n-1)
            
        return count

012 数值的整数次方

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        return pow(base,exponent)

013 调整数组顺序使奇数位于偶数前面

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        lista=[]
        
        for i in range(len(array)):
            if array[i] %2 !=0:
                lista.append(array[i])
        for i in range(len(array)):
            if array[i] %2 ==0:
                lista.append(array[i])
        return lista

014 链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个结点。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        slow=head
        fast=head
        for  i in range(k):
            if fast==None:
                return None
            fast=fast.next
        while fast:
            slow=slow.next
            fast=fast.next
        return slow

015 反转链表

输入一个链表,反转链表后,输出新链表的表头。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        
        nextnode=None
        pre=None
        if pHead ==None:
            return None
        
        while pHead:
            nextnode=pHead.next
            pHead.next=pre
            pre=pHead
            pHead=nextnode
        return pre

016 合并两个排序的链表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        while pHead1 ==None:
            return pHead2
        while pHead2==None:
            return pHead1
        rootnode=ListNode(0)
        mergenode=rootnode
        while pHead1 and pHead2 :
            if pHead1.val<pHead2.val:
                mergenode.next=pHead1
                pHead1=pHead1.next
                mergenode=mergenode.next
                
            else:
                mergenode.next=pHead2
                pHead2=pHead2.next
                mergenode=mergenode.next
                
        if pHead1:
            mergenode.next=pHead1
        if  pHead2:
            mergenode.next=pHead2
        return rootnode.next

017 树的子结构

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
def hasEqual(p1,p2):
    if p1==None:
        return False
    if p2==None:
        return True
    if p1.val==p2.val:
        if p2.left ==None:
            leftequl= True
        else:
            leftequl=hasEqual(p1.left,p2.left)
        if p2.right ==None:
            rightequl= True
        else:
            rightequl=hasEqual(p1.right,p2.right)
        return leftequl and rightequl
    return False
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        if pRoot1== None:
            return False
        if pRoot2 == None:
            return False
        if pRoot1.val== pRoot2.val:
            ret=hasEqual(pRoot1,pRoot2)
            if ret:
                return True
        ret=self.HasSubtree(pRoot1.left,pRoot2)
        if ret:
            return True
        ret=self.HasSubtree(pRoot1.right,pRoot2)
        return ret

018 二叉树的镜像

操作给定的二叉树,将其变换为源二叉树的镜像。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if root ==None:
            return None
        #处理根节点
        root.left,root.right=root.right,root.left
        self.Mirror(root.left)
        self.Mirror(root.right)
        #处理左子树
        #处理右子树
        

019 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        result=[]
        while(matrix):
            result+=matrix.pop(0)
            if not matrix or not matrix[0]:
                break            #if防止越界
            matrix=self.turn(matrix)
        return result
    def turn(self,matrix):
        nrow=len(matrix)
        ncol=len(matrix[0])
        newMatrix=[]
        for i in range(ncol):
            sb=[]
            for j in range(nrow):
                sb.append(matrix[j][i]) #取矩阵的每列第i列
            newMatrix.append(sb)
        newMatrix.reverse()#翻转
        return newMatrix

020 包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack=[]
        self.minvalue=[]
    def push(self, node):
        self.stack.append(node)
        # write code here
        if self.minvalue ==[]:
            self.minvalue.append(node)
        else:
            if self.minvalue[-1] >node:
                self.minvalue.append(node)
            else:
                self.minvalue.append(self.minvalue[-1])
    def pop(self):
        
        if self.stack:
            self.minvalue.pop()
            return self.stack.pop()
        else:
            return None
        # write code here
    def top(self):
        if self.stack:
            return self.stack[-1]
        else:
            return None
        # write code herek't
    def min(self):
        # write code here
        return self.minvalue[-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值