python 刷剑指offer
编程环境python2,OJ:牛客
1.二维数组中的查找
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if len(array)==0 or len(array[0])==0:
return False
i = 0
j = len(array[0])-1
while(i<len(array) and j>=0):
if array[i][j]==target:
return True
elif array[i][j]>target:
j-=1
else:
i+=1
return False
2.替换空格
class Solution:
# s 源字符串
def replaceSpace(self, s):
#def replaceSpaceByAppend(self, s):
if s == None:
return None
if len(s) == 0:
return ''
result = ''
for item in s:
if item.isspace():
result = result+'%20'
else:
result = result+item
return result
3.从头到尾打印链表
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
ret = []
head = listNode
while(head):
ret.append(head.val)
head = head.next
ret.reverse()
return ret
4.重建二叉树
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
if pre==[]:
return None
val = pre[0]
idx = tin.index(val)
ltin = tin[0:idx]
rtin = tin[idx+1:]
lpre = pre[1:1+len(ltin)]
rpre = pre[1+len(ltin):]
root = TreeNode(val)
root.left = self.reConstructBinaryTree(lpre,ltin)
root.right = self.reConstructBinaryTree(rpre,rtin)
return root
5.用两个栈实现队列
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 len(self.stack2):
return self.stack2.pop()
while(self.stack1):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
6.旋转数组的最小数字
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if rotateArray == []:
return 0
_len = len(rotateArray)
left = 0
right = _len -1
while left <= right:
mid = int((left + right) >> 1)
if rotateArray[mid] < rotateArray[mid - 1]:
return rotateArray[mid]
if rotateArray[mid] >= rotateArray[right]:
left = mid + 1
else:
right = mid - 1
return rotateArray[mid]