一、二维数组中的查找
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
row=0
col=len(array[0])-1
if array==None:
return False
while row<len(array) and col>=0:
if array[row][col]==target:
return True
if array[row][col]>target:
col-=1
else:
row+=1
return False
二、替换空格
class Solution:
# s 源字符串
def replaceSpace(self, s):
result=[]
for i in s:
if i ==' ':
result.append("%20")
else:
result.append(i)
return "".join(result)
三、从尾到头打印链表
# -*- 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
out=[]
if listNode is None:
return out
while listNode.next is not None:
out.append(listNode.val)
listNode=listNode.next
out.append(listNode.val)
out.reverse()
return out
四、重建二叉树
# -*- 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
if len(pre)==1:
return TreeNode(pre[0])
else:
res=TreeNode(pre[0])
res.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
res.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1 :], tin[tin.index(pre[0])+1 :])
return res
五、两个队列实现一个栈
class Stack:
def __init__(self):
self.queueA=[]
self.queueB=[]
def push(self, node):
self.queueA.append(node)
def pop(self):
if len(self.queueA)==0:
return None
while len(self.queueA)!=1:
self.queueB.append(self.queueA.pop(0))
self.queueA,self.queueB=self.queueB,self.queueA
return self.queueB.pop()
if __name__=='__main__':
times=5
testList=list(range(times))
testStock=Stack()
for i in range(times):
testStock.push(testList[i])
print(testList)
for i in range(times):
print(testStock.pop(),',',end='')
六、两个栈实现一个队列
class Queue:
def __init__(self):
self.stack1=[]
self.stack2=[]
def push(self,node):
self.stack1.append(node)
def pop(self):
if self.stack2==[]:
if self.stack1==[]:
return None
else:
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
if __name__=='__main__':
time=5
testlist=list(range(time))
testqueue=Queue()
for i in range(time):
testqueue.push(testlist[i])
print(testlist)
for i in range(time):
print(testqueue.pop(),' ',end='')
七、旋转数组中的最小数
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
if len(rotateArray)==0:
return 0
# return min(rotateArray)
low,mid,high=0,0,len(rotateArray)-1
if rotateArray[low]<rotateArray[high]:
return rotateArray[low]
else:
while(high-low>1):
mid=(low+high)/2
if rotateArray[low]<=rotateArray[mid]:
low=mid
elif rotateArray[high]>=rotateArray[mid]:
high=mid
elif rotateArray[low]==rotateArray[high] and rotateArry[low]==rotateArray[mid]:
for i in range(len(rotateArray)):
if rotateArray[i]<rotateArray[0]:
result=rotateArray[i]
high=i
result=rotateArray[high]
return result