python solution collection of sword finger offer (continuous update)

Posted by crazydip on Thu, 30 Jan 2020 09:18:18 +0100

Trapped at home by the epidemic, I have nothing to do to brush my sword and point at offer. Here is a collection of questions and solutions, which hasn't been completed yet
20190129: 15 Ways

Article directory

Interview question 3: repeated numbers in the array

  • Title Description
    All numbers in an array of length n are in the range of 0 to n-1. Some numbers in the array are repeated, but I don't know how many are. I don't know how many times each number is repeated. Please find any duplicate number in the array. For example, if the input length is 7 array {2,3,1,0,2,5,3}, the corresponding output is the first repeated number 2.
# -*- coding:utf-8 -*-
class Solution:
    # Special attention here ~ find an arbitrary duplicate value and assign it to duplication[0]
    # Function returns True/False
    def duplicate(self, numbers, duplication):
        # write code here
        for i, m in enumerate(numbers):
            if i == m:
                continue
            else:
                if numbers[m] == m:
                    duplication[0] = m
                    return True
                else:
                    numbers[i] = numbers[m]
                    numbers[m] = m
        return False

Interview question 4: search in two-dimensional array

  • Title Description
    In a two-dimensional array (the length of each one-dimensional array is the same), each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.
# -*- coding:utf-8 -*-
class Solution:
    # array 2D list
    def Find(self, target, array):
        # write code here
        i = len(array) - 1
        j = 0
        while i!=0 or j != len(array[0]) - 1:
            if i < 0 or j > len(array[0]) - 1:
                return False
            n = array[i][j]
            if n > target:
                i -= 1
            elif n < target:
                j += 1
            else:
                return True

Interview question 5: replace space

  • Title Description
    Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.
# -*- coding:utf-8 -*-
class Solution:
    # s source string
    def replaceSpace(self, s):
        # write code here
        s = s.replace(' ', '%20')
        return s

Interview question 6: print the linked list from the end to the end

  • Title Description
    Enter a linked list and return an ArrayList from the end to the end of the list.
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # Returns a sequence of list values from the tail to the head, for example [1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        re = []
        while listNode:
            re.append(listNode.val)
            listNode = listNode.next
        return re[::-1]

Interview question 7: reconstruction of binary tree

  • Title Description
    Enter the results of the preorder traversal and inorder traversal of a binary tree, and rebuild the binary tree. It is assumed that the results of the input preorder traversal and preorder traversal do not contain duplicate numbers. For example, if the sequence {1,2,4,7,3,5,6,8} and the sequence {4,7,2,1,5,3,8,6} are input, the binary tree will be reconstructed and returned.
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # Returns the TreeNode root node of the construct
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre) == 0:
            return None
        root_val = pre[0]
        root = TreeNode(root_val)
        idx = tin.index(root_val)
        if idx == 0:
            left_tree = None
        else:
            left_tree = self.reConstructBinaryTree(pre[1:idx+1], tin[:idx])
        if idx == len(pre) - 1:
            right_tree = None
        else:
            right_tree = self.reConstructBinaryTree(pre[idx+1:], tin[idx+1:])
        root.left = left_tree
        root.right = right_tree
        return root

Interview question 8: next node of binary tree

  • Title Description
    Given a binary tree and one of its nodes, find the next node in the middle order traversal order and return. Note that the nodes in the tree contain not only left and right child nodes, but also pointers to the parent nodes.
# -*- coding:utf-8 -*-
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None
class Solution:
    def GetNext(self, pNode):
        # write code here
        if pNode.right:
            pNode = pNode.right
            while pNode.left:
                pNode = pNode.left
            return pNode
        while pNode:
            if pNode.next:
                if pNode.next.left == pNode:
                    return pNode.next
                pNode = pNode.next
            else:
                return None

Interview question 9: using two stacks to implement the queue

  • Title Description
    Two stacks are used to implement a queue, and the Push and Pop operations of the queue are completed. The element in the queue is of type int.
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
        
    def push(self, node):
        # write code here
        while self.stack2:
            self.stack1.append(self.stack2.pop())
        self.stack1.append(node)
        
    def pop(self):
        # return xx
        while self.stack1:
            self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

Interview question 10: Fibonacci series

  • Title Description
    Everyone knows the Fibonacci sequence. Now you need to input an integer n. please output the nth term of the Fibonacci sequence (starting from 0, 0).
    n<=39
# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        if n <= 0:
            return 0
        if n == 1:
            return 1
        i = 2
        a, b = 0, 1
        while i <= n:
            s = a + b
            a, b = b, s
            i += 1
        return s

Interview question 11: minimum number of rotation array

  • Title Description
    To move the first elements of an array to the end of the array, we call it the rotation of the array.
    Input a rotation of a non decrementing array, and output the minimum elements of the rotation array.
    For example, array {3,4,5,1,2} is a rotation of {1,2,3,4,5} and the minimum value of the array is 1.
    NOTE: all the given elements are greater than 0. If the array size is 0, please return 0.
# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if not rotateArray:
            return 0
        left = 0
        right = len(rotateArray) - 1
        while left < right:
            if rotateArray[left]<rotateArray[right]:
                return rotateArray[left]
            mid = (right + left) // 2
            if rotateArray[left] < rotateArray[mid]:
                left = mid
            elif rotateArray[mid] > rotateArray[right]:
                right = mid
            else:
                right -= 1
        return rotateArray[mid+1]

Interview question 12: path in matrix

  • Title Description
    Please design a function to determine whether there is a path containing all characters of a string in a matrix. The path can start from any lattice in the matrix, and each step can move one lattice left, right, up and down in the matrix. If a path passes through a lattice in the matrix, the path can no longer enter the lattice. For example, the a b c e s f c s a d e matrix contains a path of the string "bcced", but the matrix does not contain a path of "abcb", because after the first character B of the string occupies the second lattice in the first row of the matrix, the path cannot enter the lattice again.
# -*- coding:utf-8 -*-
class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        for i in range(len(matrix)):
            if matrix[i] == path[0]:
                if self.isPath(matrix, rows, cols, i, path):
                    return True
        return False
    
    def isPath(self, matrix, rows, cols, i, path):
        if matrix[i] != path[0]:
            return False
        if len(path) == 1:
            return True
        # You can set a matrix to mark whether a grid has been passed
        matrix = matrix[:i] + '#' + matrix[i+1:]
        up = self.isPath(matrix, rows, cols, i-cols, path[1:]) if i >= cols else False
        down = self.isPath(matrix, rows, cols, i+cols, path[1:]) if i < len(matrix) - cols else False
        right = self.isPath(matrix, rows, cols, i+1, path[1:]) if ((i+1) % cols != cols and i+1 < len(matrix)) else False
        left = self.isPath(matrix, rows, cols, i-1, path[1:]) if (i % cols != cols and i-1>0) else False
        return up or down or left or right

Interview question 13: range of motion of robot

  • Title Description
    There is a grid of m rows and n columns on the ground. A robot starts to move from the grid of coordinates 0,0. Each time, it can only move one grid to the left, right, up and down directions, but it can't enter the grid where the sum of the row coordinates and the column coordinates is greater than k. For example, when k is 18, the robot can enter the grid (35, 37), because 3 + 5 + 3 + 7 = 18. However, it cannot enter the grid (35,38) because 3 + 5 + 3 + 8 = 19. How many squares can the robot reach?
# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        return len(self.spaceCount(set(), 0, 0, threshold, rows, cols))
        
    def spaceCount(self, re, i, j, threshold, rows, cols):
        if self.get_bitsum(i) + self.get_bitsum(j) > threshold or (i, j) in re:
            return re
        re.add((i,j))
        if i + 1 < rows:
            re = self.spaceCount(re, i+1, j, threshold, rows, cols)
        if j + 1 < cols:
            re = self.spaceCount(re, i, j+1, threshold, rows, cols)
        return re

    def get_bitsum(self, num):
        s = 0
        while num>0:
            s += num % 10
            num = num // 10
        return s

Interview question 14: cutting rope

  • Title Description
    To give you a rope of length N, please cut the rope into integral length m segments (m, n are integers, n > 1 and M > 1). The length of each segment of rope is recorded as k[0],k[1] k[m]. Excuse me, k[0]xk[1]x What is the possible maximum product of xk[m]? For example, when the length of a rope is 8, we cut it into three sections with the length of 2, 3 and 3, and the maximum product is 18.
# -*- coding:utf-8 -*-
class Solution:
    def cutRope(self, number):
        # write code here
        if number < 2: return 0
        if number == 2:return 1
        if number == 3:return 2
        products = [0, 1, 2, 3]
        for i in range(4, number+1, 1):
            product = 0
            for j in range(1,i//2+1):
                res = products[j]* products[i-j]
                product = max(res,product)
                products.append(product)
        return products[-1]

Interview question 15: number of 1 in binary

  • Title Description
    Enter an integer and output the number of 1 in the binary representation of the number. Negative numbers are represented by complement.
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        count=0
        if n < 0:
            n = n & 0xffffffff
        while n!=0:
            n=n&(n-1)
            count+=1
        return count
Published 15 original articles, won praise 14, visited 3451
Private letter follow