剑指offer 牛客网 Python刷题

1.二维数组中的查找

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        len_row=len(array)-1
        len_col=len(array[0])-1
        row=0
        col=len_col
        if array == None:
            return False
        while row<=len_row and col>=0:
            if array[row][col]target:
                col -= 1
            else:
                return True
        return False

def main():
    array=[[1,2,3],[4,5,6],[7,8,9]]
    print Find(5,array)
if __name__=="__main__":
    main()

2.替换空格

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

3.从尾到头打印空格

# -*- 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
        output=[]
        head=listNode
        while head != None:
            output.append(head.val)
            head=head.next
        output.reverse()
        return output

4.重建二叉树

# -*- 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
        root=TreeNode(pre[0])
        root.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
        root.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
        return root

5.用两个栈实现队列

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

6.旋转数组的最小数字

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if len(rotateArray)==0:
            return 0
        left=0
        right=len(rotateArray)-1
        middle=left
        while rotateArray[left]>=rotateArray[right]:
            if right-left==1:
                middle=right
                break
            middle=(left+right)//2
            if rotateArray[left]<=rotateArray[middle]:
                left=middle
            elif rotateArray[right]>=rotateArray[middle]:
                right=middle
        return rotateArray[middle]

7.斐波那契数列

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.dictionary={0:0,1:1}
    def Fibonacci(self, n):
        # write code here
        if n in self.dictionary:
            return self.dictionary[n]
        else:
            fn=self.Fibonacci(n-1)+self.Fibonacci(n-2)
            self.dictionary[n]=fn
            return fn

8.跳台阶

# -*- coding:utf-8 -*-
class Solution:    
    def __init__(self):
        self.dictionary={1:1,2:2}
    def jumpFloor(self, number):
        # write code here
        if number in self.dictionary:
            return self.dictionary[number]
        else:
            self.dictionary[number]=self.jumpFloor(number-1)+self.jumpFloor(number-2)
        return self.dictionary[number]
        

9.变态跳台阶

# -*- coding:utf-8 -*-
class Solution:
    def jumpFloorII(self, number):
        # write code here
        if number==1:
            return number
        else:
            return 2*self.jumpFloorII(number-1)
        

10.矩形覆盖

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

11.二进制中1的个数

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        if n >= 0:
            return bin(n).count('1')
        else:
            return bin(n & 0xffffffff).count('1')
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        count=0
        for i in range(32):
            count+=((n>>i)&1)
        return count

12.数值的整数次方

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

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

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

14.链表中的倒数第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
        a=[]
        while head:
            a.append(head)
            head=head.next
        if k>=1 and k<=len(a):
            return a[-k]

15.反转链表

# -*- 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
        if not pHead or not pHead.next:
            return pHead
        last=None
        while pHead:
            t=pHead.next
            pHead.next=last
            last=pHead
            pHead=t
        return last

16.合并两个排序的链表

# -*- 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
        pHead=ListNode(20)
        p=pHead
        
        while pHead1 and pHead2:
            if pHead1.val

17.树的子结构

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        if pRoot1==None:
            return False
        if pRoot2==None:
            return False
        return self.IfSubtree(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
    
    def IfSubtree(self, proot1, proot2):
        if proot2==None:
            return True
        if proot1==None:
            return False
        if proot1.val!=proot2.val:
            return False
        return self.IfSubtree(proot1.left,proot2.left) and self.IfSubtree(proot1.right,proot2.right)

18.二叉树的镜像

# -*- 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:
            root.left,root.right=root.right,root.left
            self.Mirror(root.left)
            self.Mirror(root.right)
        
        return root

19.顺时针打印矩阵

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        a = []
        row = len(matrix)
        col = len(matrix[0])

        for i in range(0, (min(row, col) + 1) // 2):
            for j in range(i, col - i):
                a.append(matrix[i][j])
            for j in range(i+1 , row - i):
                if matrix[j][col - i-1] not in a:
                    a.append(matrix[j][col- i-1])

            for j in range(i, col - i - 1):
                if matrix[row - i-1][col-j-2] not in a:
                    a.append(matrix[row - i-1][col-j-2])

            for j in range(i+1 , row - i - 1):
                if matrix[row-j-1][i] not in a:
                    a.append(matrix[row-j-1][i])
        return a

20.包含min函数的栈

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack=[]
    def push(self, node):
        # write code here
        return self.stack.append(node)
    def pop(self):
        # write code here
        return self.stack.pop()
    def top(self):
        # write code here
        return self.stack[-1]
    def min(self):
        # write code here
        return min(self.stack)

21.栈的压入、弹出序列

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if len(pushV)!=len(popV):
            return False
        stack=[]
        for x in pushV:
            stack.append(x)
            while len(stack) and stack[-1]==popV[0]:
                stack.pop()
                popV.pop(0)
        if len(stack):
            return False
        return True

22.从上往下打印二叉树

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        a=[]
        result=[]
        a=[root]
        while a:
            currentroot=a.pop(0)
            result.append(currentroot.val)
            if currentroot.left:
                a.append(currentroot.left)
            if currentroot.right:
                a.append(currentroot.right)
        return result

23.二叉搜索树的后序遍历序列

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if not sequence:
            return False
        
        root=sequence[-1]
        length=len(sequence)
        
        for i in range(length):
            if sequence[i]>root:
                break
        for j in range(i,length-1):
            if sequence[j]0:
            leftis=self.VerifySquenceOfBST(left)
        if len(right)>0:
            rightis=self.VerifySquenceOfBST(right)
        return leftis and rightis

24.二叉树中和为某一值的路径

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        if not root:
            return []
        
        if not root.left and not root.right and root.val==expectNumber:
            return [[root.val]]
        
        result=[]
        left=self.FindPath(root.left,expectNumber-root.val)
        right=self.FindPath(root.right,expectNumber-root.val)
        
        for i in left+right:
            result.append([root.val]+i)
        
        return result

25.复杂链表的复制

# -*- coding:utf-8 -*-
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        # write code here
        if not pHead:
            return None
        p=RandomListNode(pHead.label)
        p.next=pHead.next
        p.random=pHead.random
        p.next=self.Clone(pHead.next)
        return p

26.二叉搜索树与双向链表

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return pRootOfTree
        if not pRootOfTree.left and not pRootOfTree.right:
            return pRootOfTree
        
        self.Convert(pRootOfTree.left)
        left=pRootOfTree.left
        if left:
            while left.right:
                left=left.right
            left.right=pRootOfTree
            pRootOfTree.left=left
        
        self.Convert(pRootOfTree.right)
        right=pRootOfTree.right
        if right:
            while right.left:
                right=right.left
            right.left=pRootOfTree
            pRootOfTree.right=right
        
        while pRootOfTree.left:
            pRootOfTree=pRootOfTree.left
            
        return pRootOfTree

27.字符串的排列

# -*- coding:utf-8 -*-
import itertools
class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss:
            return []
        if len(ss)==1:
            return [ss]
        
        return sorted(list(set(map(''.join,itertools.permutations(ss)))))

28.数组中出现次数超过一半的数字

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        
        length=len(numbers)
        dictionary={}
        
        for i in numbers:
            if not dictionary.get(i):
                dictionary[i]=1
            elif dictionary.get(i):
                dictionary[i]+=1
        
        maxnium=max(dictionary,key=dictionary.get)
        
        if dictionary.get(maxnium) >length//2:
            return maxnium
        else: 
            return 0

29.最小的K个数

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if len(tinput)

30.连续子数组的最大和

# -*- coding:utf-8 -*-
class Solution:
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        if not array:
            return []
        
        thesum=0
        maxlist=[]
        
        for i in range(len(array)):
            thesum=array[i]
            maxlist.append(thesum)
            for j in range(i+1,len(array)):
                thesum+=array[j]
                maxlist.append(thesum)
        
        return max(maxlist)

31.整数中1出现的次数(从1到n整数中1出现的次数)

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        count=0
        
        for i in range(1,n+1):
            for x in str(i):
                if x=='1':
                    count+=1
                    
        return count

32.把数组排成最小的数

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if not numbers:
            return ""

        l = sorted(numbers, lambda x,y:cmp(str(x) + str(y), str(y) + str(x)))

        return "".join(str(x) for x in l)

 

你可能感兴趣的:(剑指offer 牛客网 Python刷题)