1.二维数组的查找(数组)
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
#将target与列表的左下角元素比较,若target大于左下角元素,列右移;小于行上移
if len(array)==0:
return "false"
col=len(array[0])
row=len(array)
j=0
i=row-1
while j<=col-1 and i>=0:
if(target==array[i][j]):
return "true"
break
elif(target
i-=1
else:
j+=1
return "false"
while True:
try:
S=Solution()
#字符串转为list
L=list(eval(raw_input()))
array=L[1]
target=L[0]
print(S.Find(target,array))
except:
break
2.替换空格(字符串)
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
#str不可变 将str转为list
s=list(s)
s_len=len(s)
for i in range(0,s_len):
if(s[i]==" "):
s[i]="%20"
return "".join(s)
3.从尾到头打印链表(链表)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
#用栈的方式实现
list=[]
if listNode==None:
return list
while listNode.next:
list.append(listNode.val)
listNode=listNode.next
list.append(listNode.val)
return list[::-1]
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
if(len(pre)==1):
return TreeNode(pre[0])
else:
root=TreeNode(pre[0])
pos=tin.index(root.val)
root.left=self.reConstructBinaryTree(pre[1:pos+1],tin[0:pos])#数组上界不包括该值
root.right=self.reConstructBinaryTree(pre[pos+1:],tin[pos+1:])
return root
5.二叉树镜像(树)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
if root !=None:
root.left,root.right = root.right,root.left
self.Mirror(root.left)
self.Mirror(root.right)