1. 程式人生 > 其它 >小米6刷MIUI12.5(miui12.5)超級詳細教程

小米6刷MIUI12.5(miui12.5)超級詳細教程

技術標籤:資料結構與演算法python

1.二維陣列中的查詢
題目: 在一個二維陣列中(每個一維陣列的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。

**思路:**遍歷每一行,查詢該元素是否在該行之中。

class Solution:
# array 二維列表
def Find(self, target, array):
# write code here
for line in array:
if target in line:
return True
return False

if name==‘main’:
target=2
array=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]]
solution=Solution()
ans=solution.Find(target,array)
print(ans)
2.替換空格
題目: 請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

**思路:**利用字串中的replace直接替換即可。

class Solution:
# s 源字串
def replaceSpace(self, s):

# write code here
temp = s.replace(" ", “%20”)
return temp

if name==‘main’:
s=‘We Are Happy’
solution=Solution()
ans=solution.replaceSpace(s)
print(ans)
3.從尾到頭列印連結串列
**題目:**輸入一個連結串列,按連結串列值從尾到頭的順序返回一個ArrayList。

**思路:**將連結串列中的值記錄到list之中,然後進行翻轉list。

-- 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
l=[]
while listNode:
l.append(listNode.val)
listNode=listNode.next
return l[::-1]

if name==‘main’:
A1 = ListNode(1)
A2 = ListNode(2)
A3 = ListNode(3)
A4 = ListNode(4)
A5 = ListNode(5)

A1.next=A2
A2.next=A3
A3.next=A4
A4.next=A5

solution=Solution()
ans=solution.printListFromTailToHead(A1)
print(ans)

4.重建二叉樹
**題目:**輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

**題解:**首先前序遍歷的第一個元素為二叉樹的根結點,那麼便能夠在中序遍歷之中找到根節點,那麼在根結點左側則是左子樹,假設長度為M.在根結點右側,便是右子樹,假設長度為N。然後在前序遍歷根節點後面M長度的便是左子樹的前序遍歷序列,再後面的N個長度便是右子樹的後序遍歷的長度。
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:
flag=TreeNode(pre[0])
flag.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
flag.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
return flag

if name==‘main’:
solution=Solution()
pre=list(map(int,input().split(’,’)))
tin=list(map(int,input().split(’,’)))
ans=solution.reConstructBinaryTree(pre,tin)
print(ans.val)