剑指offer刷题笔记

由于本人的主力语言为python,以下面试题都用python实现

面试题之二:实现Singleton模式

题目:实现一个单例模式

class Singleton(object):
    _instance = None
    _instance_lock = threading.Lock()

    def __init__(self, *args, **kwargs):
        pass

    def __new__(cls, *args, **kwargs):
        if cls._instance:
            return cls._instance
        with cls._instance_lock:
        	cls._instance = object.__new__(cls)
        return cls._instance

面试题之三:二维数组中的查找

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

例如下面的数组,如果查找数字7,则返回True;如果查找数字5,则返回False

[
    [1,2,8,9],
    [2,4,9,12],
    [4,7,10,13],
    [6,8,11,15]
]

思路:

1.从左下角开始选取元素,将此元素与目标元素比较,有三种可能的情况

1)此元素与目标元素相等,返回True,程序结束

2)此元素小于目标元素,则在这个元素的右侧开始查找

3)此元素大于目标元素,则在这个元素的上侧开始查找

2.重复步骤1,直到结束,返回False

代码

def find_in_partially_sorted_matrix(matrix, num):
    '''
    :type matrix: List[List[int]]
    :type num: int
    :rtype: bool
    '''
    if not matrix or not matrix[0]:
        return False
    if num < matrix[0][0] or num > matrix[-1][-1]:
        return False

    i, j = len(matrix) - 1, 0
    while i >= 0 and j <= len(matrix[0]) - 1:
        if matrix[i][j] == num:
            return True
        elif matrix[i][j] < num:
            j += 1
        elif matrix[i][j] > num:
            i -= 1
    return False


if __name__ == '__main__':
    matrix = [
                [1, 2, 8, 9],
                [2, 4, 9, 12],
                [4, 7, 10, 13],
                [6, 8, 11, 15]
            ]
    #print(find_in_partially_sorted_matrix(matrix, 10))
    #print(find_in_partially_sorted_matrix(matrix, 4))
    #print(find_in_partially_sorted_matrix(matrix, 15))
    #print(find_in_partially_sorted_matrix(matrix, 9))
    #print(find_in_partially_sorted_matrix(matrix, 5))
    #print(find_in_partially_sorted_matrix(matrix, -1))
    #print(find_in_partially_sorted_matrix(matrix, 1))
    #print(find_in_partially_sorted_matrix(matrix, 18))

    matrix = [
            [-2, 1, 5, 9]
            ]
    #print(find_in_partially_sorted_matrix(matrix, -2))
    #print(find_in_partially_sorted_matrix(matrix, 5))
    #print(find_in_partially_sorted_matrix(matrix, 9))
    #print(find_in_partially_sorted_matrix(matrix, -1))
    #print(find_in_partially_sorted_matrix(matrix, -3))
    #print(find_in_partially_sorted_matrix(matrix, 10))

    matrix = [
            [-5,],
            [-2,],
            [3,],
            [6,],
            [8,]
            ]
    #print(find_in_partially_sorted_matrix(matrix, 0))
    #print(find_in_partially_sorted_matrix(matrix, -8))
    #print(find_in_partially_sorted_matrix(matrix, 6))
    #print(find_in_partially_sorted_matrix(matrix, 8))
    #print(find_in_partially_sorted_matrix(matrix, -5))
    #print(find_in_partially_sorted_matrix(matrix, 10))

    matrix = []
    #print(find_in_partially_sorted_matrix(matrix, 3))

    matrix = [
            [],
            [],
            []
            ]
    print(find_in_partially_sorted_matrix(matrix, 5)) 

面试题之五:从尾到头打印链表

class ListNode(object):

    def __init__(self, val):
        self.val = val
        self.next = None

def print_list_node_reversingly(head: ListNode) -> None:
    stack = []
    p = head
    while p is not None:
        stack.append(p.val)
        p = p.next
    while len(stack) != 0:
        print(stack.pop())


if __name__ == '__main__':
    p1 = ListNode(1)
    p2 = ListNode(2)
    p3 = ListNode(3)
    p4 = ListNode(4)
    p1.next = p2
    p2.next = p3
    p3.next = p4
    print_list_node_reversingly(p1)

    p1 = ListNode(1)
    print_list_node_reversingly(p1) 
    p = None
    print_list_node_reversingly(p)

面试题之六:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,输出二叉树的头结点

from typing import List


class TreeNode(object):
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


def construct_binary_tree(preorder: List[int], inorder: List[int]) -> TreeNode:
    """重建二叉树"""
    if len(preorder) == 0:
        return None
    if len(preorder) == 1:
        root = TreeNode(preorder[0])
        return root
    index = inorder.index(preorder[0])
    left_child_preorder = preorder[1:index + 1]
    right_child_preorder = preorder[index + 1:]
    left_child_inorder = inorder[:index]
    right_child_inorder = inorder[index + 1:]
    root = TreeNode(preorder[0])
    root.left = construct_binary_tree(left_child_preorder, left_child_inorder)
    root.right = construct_binary_tree(right_child_preorder, right_child_inorder)

    return root


def level_order_travel(root: TreeNode) -> List:
    """输出宽度优先遍历的结果,用于验证"""
    levels = []
    if not root:
        return levels

    def helper(node: TreeNode, level: int) -> None:
        if len(levels) == level:
            levels.append([])

        levels[level].append(node.val)

        if node.left:
            helper(node.left, level + 1)
        if node.right:
            helper(node.right, level + 1)

    helper(root, 0)
    return levels


if __name__ == '__main__':
    preorder = [3, 9, 20, 15, 7]
    inorder = [9, 3, 15, 20, 7]
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))

    preorder = [1, 2, 4, 8, 9, 14, 5, 10, 11, 3, 6, 12, 13, 7]
    inorder = [8, 4, 14, 9, 2, 10, 5, 11, 1, 12, 6, 13, 3, 7]
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))

    preorder = [1, 2, 3]
    inorder = [1, 3, 2]
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))
    
    preorder = [1, 2, 3]
    inorder = [3, 2, 1]
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))
 
    preorder = [1, 2, 3]
    inorder = [1, 2, 3]
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))
 
    preorder = [2]
    inorder = [2] 
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))

    preorder = []
    inorder = []
    root = construct_binary_tree(preorder, inorder)
    print(level_order_travel(root))

面试题之七:用两个栈实现队列

题目:用两个栈实现队列,分别完成在尾部插入结点和在队列头部删除结点的功能

class Stack(object):

    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if not self.stack:
            return "empty stack!"
        return self.stack.pop()

    def is_empty(self):
        return len(self.stack) == 0


class MyQueue(object):

    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()

    def append_tail(self, item):
        self.stack1.push(item)

    def delete_head(self):
        if not self.stack2.is_empty():
            return self.stack2.pop()
        if self.stack1.is_empty():
            return "empty queue!"
        while not self.stack1.is_empty():
            self.stack2.push(self.stack1.pop())
        return self.stack2.pop()


if __name__ == "__main__":
    q1 = MyQueue()
    q1.append_tail(1)
    q1.append_tail(2)
    q1.append_tail(3)
    print(q1.delete_head())
    print(q1.delete_head())
    print(q1.delete_head())
    print(q1.delete_head())

    print("-------------------")

    q2 = MyQueue()
    q2.append_tail(1)
    print(q2.delete_head())
    print(q2.delete_head())
    q2.append_tail(2)
    q2.append_tail(3)
    print(q2.delete_head())

补充:用两个队列实现栈

题目:用两个队列实现栈,分别完成压入和弹出功能

from queue import Queue


class Stack(object):

    def __init__(self):
        self.queue1 = Queue()
        self.queue2 = Queue()

    def push(self, item):
        if self.queue1.empty():
            self.queue2.put(item)
        else:
            self.queue1.put(item)

    def pop(self):
        if self.queue1.empty() and self.queue2.empty():
            return "empty stack!"
        if self.queue1.empty():
            while not self.queue2.empty():
                item = self.queue2.get()
                if self.queue2.empty():
                    return item
                self.queue1.put(item)
        else:
            while not self.queue1.empty():
                item = self.queue1.get()
                if self.queue1.empty():
                    return item
                self.queue2.put(item)
                
                
if __name__ == "__main__":
    s1 = Stack()
    s1.push(1)
    s1.push(2)
    print(s1.pop())
    print(s1.pop())
    print(s1.pop())

    print("--------------")

    s2 = Stack()
    print(s2.pop())
    s2.push(1)
    s2.push(2)
    print(s2.pop())
    s2.push(3)
    print(s2.pop())
    print(s2.pop())
    print(s2.pop())   

持续更新中...

posted @ 2020-02-26 17:55  乘月归  阅读(275)  评论(0编辑  收藏  举报