剑指Offer-Python(1-5)

1、二维数组的查找

查找,其实就可以挨个进行比较就可以。又由于题目说明(每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序),因此如果利用类似于二分查找的方法,那么比较次数则会更少。代码中以第一行最后一列的元素作为第一个比较的元素,比目标元素大则按行往左找,比目标元素小则按列往下找,直到找到或者下标溢出。

def Find(target, array):
    # write code here
    row = len(array)
    col = len(array[0])
    i = 0
    j = col - 1
    while i < row and j >= 0:
        if target < array[i][j]:
            j = j - 1
        elif target > array[i][j]:
            i = i + 1
        else:
            return True
    return False


array = [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]]
target = 7
# row = len(array)
# col = len(array[0])
# print(row, "  ", col)
print(Find(target, array))

2、替换空格

def replaceSpace(s):
    t = s.replace(' ', '%20')
    return t

s = "We Are Happy"
print(replaceSpace(s))

3、从头到尾打印链表

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


# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(listNode):
    l = []
    while listNode:
        l.append(listNode.val)
        listNode = listNode.next
    l.reverse()
    return l


l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l1.next = l2
l2.next = l3
l3.next = None

l = printListFromTailToHead(l1)
print(l)

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


if __name__ == '__main__':
    s = Solution()
    pre = [1, 2, 4, 7, 3, 5, 6, 8]
    tin = [4, 7, 2, 1, 5, 3, 8, 6]
    ans = s.reConstructBinaryTree(pre, tin)
    print(ans.right.val)

5、用两个栈实现队列

栈:先进后出;队列:先进先出

用两个栈s1,s2实现队列,s1负责进队列,s2负责出队列。进队:进s1即可。出队:若s1,s2都为空,则队列为空;若s2不为空,则直接取s2最后一个元素;若s2为空,则把s1内元素按从尾到头依次放入s2,再取s2最后一个元素。

# -*- 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 not self.Stack2 and not self.Stack1:
            return
        if self.Stack2:
            return self.Stack2.pop()
        else:
            while self.Stack1:
                self.Stack2.append(self.Stack1.pop())
            return self.Stack2.pop()


s = Solution()
s.push(1)
s.push(2)
s.push(3)
print(s.pop())
s.push(4)
s.push(5)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())

 

posted @ 2019-11-29 21:07  +D  阅读(208)  评论(0编辑  收藏  举报