1 二维数组中的查找
def Find(self,target,array):
if not array: #目标不在数组中
return False
rows = len(array)
cols = len(array[0])
row = 0
col = cols-1 #从右下角开始比较
while col>=0 and row<=rows-1: #保证在数组中
if array[row][col] == target: #在数组中
return Ture
elif array[row][col] <target: #数组中的值比目标数小
row+=1 #横增加哦
else:
col-=1 #列减少
return False
2 替换空格
def replaceSpace(self,s):
s = s.replace(' ','%20') #replace函数直接进行替换
return s
3 从尾到头打印单链表
class Solution:
def printListFromTailToHead(self,listNode):
stack = [] #定义一个空数组
while listNode: #在listNode里为真
stack.append(listNode.val) #添加listNode里的值到stack中
listNode = listNode.next
return stack[::-1] #[::-1]将列表或者字符倒过来
4 重建二叉树
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin): #pre为前序遍历,tin为中序遍历
# write code here
if len(pre) == 0: #如果前序遍历为空
return None
root = TreeNode(pre[0]) #根节点为前序遍历的第一个数字
i = tin.index(pre[0]) # i为根节点在中序遍历中的位置
root.left = self.reConstructBinaryTree(pre[1:1+i],tin[:i]) #获取左子树的前序遍历和中序遍历
root.right = self.reConstructBinaryTree(pre[1+i:],tin[i+1:]) #获取右子树的前序遍历和中序遍历
return root
5 用两个栈实现队列
栈是先进后出,队列是先进先出,思路:当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出。如果stack2为空时,我们把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压倒stack1的栈底,经过弹出和压入之后就处于stack2的栈顶,有可以直接弹出。如果有新元素d插入,直接把它压入stack1即可。
class Solution:
def __init__(self): #对实例的属性进行初始化
self.stack1 = []
self.stack2 = [] #定义两个空列表list
def push(self,node):
self.stack1.append(node) #将node添加到stack1
def pop(self):
if self.stack2 == []: #如果stack2是空的
while self.stack1:
self.stack2.append(self.stack1.pop()) #将stack1中的值添加到stack2中
return self.stack2.pop() #执行pop操作
return self.stack2.pop()