版权声明: https://blog.csdn.net/XiaoYi_Eric/article/details/81452014 </div><link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css"><div id="content_views" class="markdown_views prism-atom-one-dark"><!-- flowchart 箭头图标 勿删 --><svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg><h3><a name="t0"></a><a id="1_0" target="_blank"></a>1.二维数组中的查找</h3>
题目: 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
**思路:**遍历每一行,查找该元素是否在该行之中。
# -*- coding:utf-8 -*-
class Solution:# array 二维列表def Find(self, target, array):# write code herefor line in array:if target in line:return Truereturn 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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
2.替换空格
题目: 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
**思路:**利用字符串中的replace直接替换即可。
# -*- coding:utf-8 -*-
class Solution:# s 源字符串def replaceSpace(self, s):# write code heretemp = s.replace(" ", "%20")return temp
if name==‘main’:
s=‘We Are Happy’
solution=Solution()
ans=solution.replaceSpace(s)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
3.从尾到头打印链表
**题目:**输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
**思路:**将链表中的值记录到list之中,然后进行翻转list。
# -*- coding:utf-8 -*-
class ListNode:def __init__(self, x):self.val = xself.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<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A2
A2<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A3
A3<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A4
A4<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A5solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>printListFromTailToHead<span class="token punctuation">(</span>A1<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
4.重建二叉树
**题目:**输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
**题解:**首先前序遍历的第一个元素为二叉树的根结点,那么便能够在中序遍历之中找到根节点,那么在根结点左侧则是左子树,假设长度为M.在根结点右侧,便是右子树,假设长度为N。然后在前序遍历根节点后面M长度的便是左子树的前序遍历序列,再后面的N个长度便是右子树的后序遍历的长度。
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
5.用两个栈实现队列
**题目:**用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
**题解:**申请两个栈Stack1和Stack2,Stack1当作输入,Stack2当作pop。当Stack2空的时候,将Stack1进行反转,并且输入到Stack2。
# -*- coding:utf-8 -*-
class Solution:def __init__(self):self.Stack1=[]self.Stack2=[]def push(self, node):# write code hereself.Stack1.append(node)def pop(self):# return xxif self.Stack2==[]:while self.Stack1:self.Stack2.append(self.Stack1.pop())return self.Stack2.pop()return self.Stack2.pop()
if name==‘main’:
solution = Solution()
solution.push(1)
solution.push(2)
solution.push(3)
print(solution.pop())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
6.旋转数组的最小数字
**题目:**把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
**题解:**遍历数组寻找数组最小值。
# -*- coding:utf-8 -*-
class Solution:def minNumberInRotateArray(self, rotateArray):# write code hereminnum=999999for i in range(0,len(rotateArray)):if minnum>rotateArray[i]:minnum=rotateArray[i]if minnum:return minnumelse:return 0
if name==‘main’:
solution=Solution()
rotateArray=list(map(int,input().split(’,’)))
ans=solution.minNumberInRotateArray(rotateArray)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
7.斐波那契数列
**题目:**大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39。
**题解:**递归和非递归方法。
# -*- coding:utf-8 -*-
class Solution:def Fibonacci(self, n):# write code hereif n==0:return 0if n==1:return 1Fib=[0 for i in range(0,n+1)]Fib[0],Fib[1]=0,1for i in range(2,n+1):Fib[i]=Fib[i-1]+Fib[i-2]return Fib[n]def Fibonacci1(self,n):if n==0:return 0if n==1 or n==2:return 1else:return self.Fibonacci1(n-1)+self.Fibonacci1(n-2)
if name==‘main’:
solution=Solution()
n=int(input())
ans=solution.Fibonacci1(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
8.跳台阶
**题目:**一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
**题解:**ans[n]=ans[n-1]+ans[n-2]
class Solution:def jumpFloor(self, number):# write code hereif number==0:return 0if number==1:return 1if number==2:return 2ans=[0 for i in range(0,number+1)]ans[1],ans[2]=1,2for i in range(3,number+1):ans[i]=ans[i-1]+ans[i-2]return ans[number]
if name == ‘main’:
solution = Solution()
n=int(input())
ans=solution.jumpFloor(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
9.变态跳台阶
**题目:**一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
**题解:**ans[n]=ans[n-1]+ans[n-2]+ans[n-3]+…+ans[n-n],ans[n-1]=ans[n-2]+ans[n-3]+…+ans[n-n],ans[n]=2*ans[n-1]。
# -*- coding:utf-8 -*-
class Solution:def jumpFloorII(self, number):# write code hereif number==1:return 1if number==2:return 2return 2*self.jumpFloorII(number-1)
if name==‘main’:
solution=Solution()
n=int(input())
ans=solution.jumpFloorII(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
10.矩形覆盖
**题目:**我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
**题解:**新增加的小矩阵竖着放,则方法与n-1时相同,新增加的小矩阵横着放,则方法与n-2时相同,于是f(n)=f(n-1)+f(n-2)。
# -*- coding:utf-8 -*-
class Solution:def rectCover(self, number):# write code hereif number==0:return 0if number==1:return 1Fib=[0 for i in range(0,number+1)]Fib[1],Fib[2]=1,2for i in range(3,number+1):Fib[i]=Fib[i-1]+Fib[i-2]return Fib[number]
if name==‘main’:
solution=Solution()
n=int(input())
ans=solution.rectCover(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
11.二进制中1的个数
**题目:**输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
**题解:**每次进行左移一位,然后与1进行相与,如果是1则进行加1。
# -*- coding:utf-8 -*-
class Solution:def NumberOf1(self, n):# write code herecount = 0for i in range(32):count += (n >> i) & 1return count
if name==‘main’:
solution=Solution()
n=int(input())
ans=solution.NumberOf1(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
12.数值的整次方
**题目:**给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
# -*- coding:utf-8 -*-
class Solution:def Power(self, base, exponent):# write code hereans=1for i in range(0,abs(exponent)):ans=ans*baseif exponent>0:return anselse:return 1/ans
if name==‘main’:
solution=Solution()
base=float(input())
exponent=int(input())
ans=solution.Power(base,exponent)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
13.调整数组顺序使奇数位于偶数前面
**题目:**输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
**题解:**申请奇数数组和偶数数组,分别存放奇数值和偶数值,数组相加便为结果。
# -*- coding:utf-8 -*- class Solution:def reOrderArray(self, array):# write code herearray1=[]#奇数array2=[]#偶数
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token builtin">len</span><span class="token punctuation">(</span>array<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> array<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token operator">%</span><span class="token number">2</span><span class="token operator">!=</span><span class="token number">0</span><span class="token punctuation">:</span>array1<span class="token punctuation">.</span>append<span class="token punctuation">(</span>array<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token keyword">else</span><span class="token punctuation">:</span>array2<span class="token punctuation">.</span>append<span class="token punctuation">(</span>array<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>ans<span class="token operator">=</span>array1<span class="token operator">+</span>array2<span class="token keyword">return</span> ans
if name==‘main’:
solution=Solution()
array=list(map(int,input().split(’,’)))
ans=solution.reOrderArray(array)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
14.链表中倒数第K个节点
**题目:**输入一个链表,输出该链表中倒数第k个结点。
**题解:**反转链表,寻找第K个节点。
# -*- coding:utf-8 -*-
class ListNode:def __init__(self, x):self.val = xself.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
#反转链表
if head is None or head.next is None:
return head
pre=None #指向上一个节点
while head:
#先用temp保存当前节点的下一个节点信息
temp=head.next
#保存好next之后,便可以指向上一个节点
head.next=pre
#让pre,head指向下一个移动的节点
pre=head
head=temp
# 寻找第K个元素的位置
for i in range(1,k):
pre=pre.next
temp=pre
return temp
if name==‘main’:
solution=Solution()
k=3
p1=ListNode(1)
p2=ListNode(2)
p3=ListNode(3)
p4=ListNode(4)
p1.next=p2
p2.next=p3
p3.next=p4
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>FindKthToTail<span class="token punctuation">(</span>p1<span class="token punctuation">,</span>k<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">.</span>val<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
15.反转链表
**题目:**输入一个链表,反转链表后,输出新链表的表头。
# -*- coding:utf-8 -*-
class ListNode:def __init__(self, x):self.val = xself.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead is None or pHead.next is None:
return pHead
pre=None
while pHead:
#暂存当前节点的下一个节点信息
temp=pHead.next
#反转节点
pHead.next=pre
#进行下一个节点
pre = pHead
pHead=temp
return pre
if name==‘main’:
solution=Solution()
p1=ListNode(1)
p2=ListNode(2)
p3=ListNode(3)
p1.next=p2
p2.next=p3
ans=solution.ReverseList(p1)
print(ans.val)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
16.合并两个排序的列表
**题目:**输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
**题解:**将两个链表之中的数值转换到列表之中,并进行排序,将排序后的列表构造成链表。
# -*- coding:utf-8 -*-
class ListNode:def __init__(self, x):self.val = xself.next = None
class Solution:
# 返回合并后列表
def Merge(self,pHead1,pHead2):
# write code here
if pHead1 is None and pHead2 is None:
return None
num1,num2=[],[]
while pHead1:
num1.append(pHead1.val)
pHead1=pHead1.next
while pHead2:
num2.append(pHead2.val)
pHead2=pHead2.next
ans=num1+num2
ans.sort()
head=ListNode(ans[0])
pre=head
for i in range(1,len(ans)):
node=ListNode(ans[i])
pre.next=node
pre=pre.next
return head
if name==‘main’:
solution=Solution()
pHead1_1 = ListNode(1)
pHead1_2 = ListNode(3)
pHead1_3 = ListNode(5)
pHead1_1.next=pHead1_2
pHead1_2.next=pHead1_3
pHead2_1 <span class="token operator">=</span> ListNode<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
pHead2_2 <span class="token operator">=</span> ListNode<span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span>
pHead2_3 <span class="token operator">=</span> ListNode<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span>
pHead2_1<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>pHead2_2
pHead2_2<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>pHead2_3
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>Merge<span class="token punctuation">(</span>pHead1_1<span class="token punctuation">,</span>pHead2_1<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
17.树的子结构
**题目:**输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)。
**题解:**将树转变为中序序列,然后转变为str类型,最后判断是否包含。
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if pRoot1 is None or pRoot2 is None:
return False
pRoot1_result,pRoot2_result=[],[]
self.order_traversal(pRoot1,pRoot1_result)
self.order_traversal(pRoot2,pRoot2_result)
str1=’’.join(str(i) for i in pRoot1_result)
str2=’’.join(str(i) for i in pRoot2_result)
print(str1,str2)
if str2 in str1:
return True
else:
return False
<span class="token keyword">def</span> <span class="token function">order_traversal</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>root<span class="token punctuation">,</span>result<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> <span class="token operator">not</span> root<span class="token punctuation">:</span><span class="token keyword">return</span>self<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">,</span>result<span class="token punctuation">)</span>result<span class="token punctuation">.</span>append<span class="token punctuation">(</span>root<span class="token punctuation">.</span>val<span class="token punctuation">)</span>self<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">,</span>result<span class="token punctuation">)</span>
if name==‘main’:
solution=Solution()
pRootA1 = TreeNode(1)
pRootA2 = TreeNode(2)
pRootA3 = TreeNode(3)
pRootA4 = TreeNode(4)
pRootA5 = TreeNode(5)
pRootA1.left=pRootA2
pRootA1.right=pRootA3
pRootA2.left=pRootA4
pRootA2.right=pRootA5
pRootB2 <span class="token operator">=</span> TreeNode<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
pRootB4 <span class="token operator">=</span> TreeNode<span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span>
pRootB5 <span class="token operator">=</span> TreeNode<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>
pRootB2<span class="token punctuation">.</span>left<span class="token operator">=</span>pRootB4
pRootB2<span class="token punctuation">.</span>right <span class="token operator">=</span> pRootB5
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>HasSubtree<span class="token punctuation">(</span>pRootA1<span class="token punctuation">,</span>pRootB2<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
18.二叉树的镜像
题目: 操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5
**思路:**递归实现反转每个子节点
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
# A1_order_result=[]
# self.order_traversal(A1,A1_order_result)
if root is None:
return
if root.left is None and root.right is None:
return
temp=root.left
root.left=root.right
root.right=temp
<span class="token keyword">if</span> root <span class="token keyword">is</span> <span class="token operator">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>self<span class="token punctuation">.</span>Mirror<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">)</span><span class="token keyword">if</span> root <span class="token keyword">is</span> <span class="token operator">not</span> <span class="token boolean">None</span><span class="token punctuation">:</span>self<span class="token punctuation">.</span>Mirror<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">)</span><span class="token keyword">def</span> <span class="token function">order_traversal</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>root<span class="token punctuation">,</span>result<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> <span class="token operator">not</span> root<span class="token punctuation">:</span><span class="token keyword">return</span>self<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">,</span>result<span class="token punctuation">)</span>result<span class="token punctuation">.</span>append<span class="token punctuation">(</span>root<span class="token punctuation">.</span>val<span class="token punctuation">)</span>self<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">,</span>result<span class="token punctuation">)</span>
if name==‘main’:
A1 = TreeNode(8)
A2 = TreeNode(6)
A3 = TreeNode(10)
A4 = TreeNode(5)
A5 = TreeNode(7)
A6 = TreeNode(9)
A7 = TreeNode(11)
A1.left=A2
A1.right=A3
A2.left=A4
A2.right=A5
A3.left=A6
A3.right=A7
temp1<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span>
solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
solution<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>A1<span class="token punctuation">,</span>temp1<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>temp1<span class="token punctuation">)</span>
solution<span class="token punctuation">.</span>Mirror<span class="token punctuation">(</span>A1<span class="token punctuation">)</span>
solution<span class="token punctuation">.</span>order_traversal<span class="token punctuation">(</span>A1<span class="token punctuation">,</span>temp1<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>temp1<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
19.顺时针打印矩阵
题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下矩阵:1 2 3 45 6 7 89 10 11 1213 14 15 16 则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
**思路:**每次打印圈,但要判断最后一次是打印横还是竖,另外判断数据是否已存在。
# -*- coding:utf-8 -*-
class Solution:# matrix类型为二维列表,需要返回列表def printMatrix(self, matrix):# write code herem,n=len(matrix),len(matrix[0])res = []if n==1 and m==1:res.append(matrix[0][0])return resfor k in range(0,(min(m,n)+1)//2):[res.append(matrix[k][i]) for i in range(k, n - k)][res.append(matrix[j][n-k-1]) for j in range(k,m-k) if matrix[j][n-k-1] not in res][res.append(matrix[m-k-1][j]) for j in range(n-k-1,k-1,-1) if matrix[m-k-1][j] not in res][res.append(matrix[j][k]) for j in range(m-1-k,k-1,-1) if matrix[j][k] not in res]return res
if name==‘main’:
solution=Solution()
m,n=1,5
matrix=[]
for i in range(0,m):
matrix.append(list(map(int,input().split(’ '))))
print(matrix)
ans=solution.printMatrix(matrix)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
20.包含Min函数的栈
**题目:**定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
# -*- coding:utf-8 -*-
class Solution:def __init__(self):self.num=[]def push(self, node):# write code hereself.num.append(node)def pop(self):# write code hereself.num.pop()def top(self):# write code herenumlen = len(self.num)return self.num[numlen-1]def min(self):# write code herereturn min(self.num)
if name==‘main’:
solution = Solution()
solution.push(1)
solution.push(2)
solution.push(3)
solution.push(4)
solution.pop()
print(solution.top())
print(solution.min())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
21.栈的压入弹出序列
**题目:**输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)。
**题解:**新构建一个中间栈,来模拟栈的输入和栈的输出,比对输入结果和输出结果是否相等。
# -*- coding:utf-8 -*- class Solution:def IsPopOrder(self, pushV, popV):# write code hereif len(pushV)==1 and len(popV)==1 and pushV[0]!=popV[0]:return False
helpV<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span>pushV<span class="token punctuation">.</span>reverse<span class="token punctuation">(</span><span class="token punctuation">)</span>popV<span class="token punctuation">.</span>reverse<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token comment">#模拟给定栈的压入和压出</span>helpV<span class="token punctuation">.</span>append<span class="token punctuation">(</span>pushV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>pushV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>pushV<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span><span class="token keyword">if</span> helpV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>helpV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token operator">!=</span>popV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>popV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span>helpV<span class="token punctuation">.</span>append<span class="token punctuation">(</span>pushV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>pushV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>pushV<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token keyword">if</span> helpV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>helpV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token operator">==</span>popV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>popV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span>helpV<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token punctuation">)</span>popV<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token keyword">if</span> pushV<span class="token operator">==</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">and</span> popV<span class="token operator">==</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">and</span> helpV<span class="token operator">==</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">:</span><span class="token keyword">return</span> <span class="token boolean">True</span><span class="token keyword">if</span> pushV<span class="token operator">==</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">and</span> popV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>popV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token operator">!=</span>helpV<span class="token punctuation">[</span><span class="token builtin">len</span><span class="token punctuation">(</span>helpV<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span><span class="token keyword">return</span> <span class="token boolean">False</span>
if name==‘main’:
solution=Solution()
push=list(map(int,input().split(’ ‘)))
pop=list(map(int,input().split(’ ')))
ans=solution.IsPopOrder(push,pop)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
22.从上往下打印二叉树
**题目:**从上往下打印出二叉树的每个节点,同层节点从左至右打印。
**思路:**递归,每次将左子树结果和右子树结果存到结果集之中。
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if root is None:
return []
ans=[]
ans.append(root.val)
self.orderans(root,ans)
return ans
<span class="token keyword">def</span> <span class="token function">orderans</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>root<span class="token punctuation">,</span>ans<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> <span class="token operator">not</span> root<span class="token punctuation">:</span><span class="token keyword">return</span><span class="token keyword">if</span> root<span class="token punctuation">.</span>left<span class="token punctuation">:</span>ans<span class="token punctuation">.</span>append<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">.</span>val<span class="token punctuation">)</span><span class="token keyword">if</span> root<span class="token punctuation">.</span>right<span class="token punctuation">:</span>ans<span class="token punctuation">.</span>append<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">.</span>val<span class="token punctuation">)</span>self<span class="token punctuation">.</span>orderans<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">,</span> ans<span class="token punctuation">)</span>self<span class="token punctuation">.</span>orderans<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">,</span>ans<span class="token punctuation">)</span>
if name==‘main’:
solution=Solution()
A1 = TreeNode(1)
A2 = TreeNode(2)
A3 = TreeNode(3)
A4 = TreeNode(4)
A5 = TreeNode(5)
A1<span class="token punctuation">.</span>left<span class="token operator">=</span>A2
A1<span class="token punctuation">.</span>right<span class="token operator">=</span>A3
A2<span class="token punctuation">.</span>left<span class="token operator">=</span>A4
A2<span class="token punctuation">.</span>right<span class="token operator">=</span>A5
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>PrintFromTopToBottom<span class="token punctuation">(</span>A1<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
23.二叉树的后续遍历序列
**题目:**输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
**思路:**二叉搜索树的特性是所有左子树值都小于中节点,所有右子树的值都大于中节点,递归遍历左子树和右子树的值。
# -*- coding:utf-8 -*- class Solution:def VerifySquenceOfBST(self, sequence):# write code hereif not sequence:return Falseif len(sequence)==1:return Truei=0while sequence[i]<sequence[-1]:i=i+1k=ifor j in range(i,len(sequence)-1):if sequence[j]<sequence[-1]:return False
leftsequence<span class="token operator">=</span>sequence<span class="token punctuation">[</span><span class="token punctuation">:</span>k<span class="token punctuation">]</span>rightsequence<span class="token operator">=</span>sequence<span class="token punctuation">[</span>k<span class="token punctuation">:</span><span class="token builtin">len</span><span class="token punctuation">(</span>sequence<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span>leftans<span class="token operator">=</span><span class="token boolean">True</span>rightans<span class="token operator">=</span><span class="token boolean">True</span><span class="token keyword">if</span> <span class="token builtin">len</span><span class="token punctuation">(</span>leftsequence<span class="token punctuation">)</span><span class="token operator">></span><span class="token number">0</span><span class="token punctuation">:</span>self<span class="token punctuation">.</span>VerifySquenceOfBST<span class="token punctuation">(</span>leftsequence<span class="token punctuation">)</span><span class="token keyword">if</span> <span class="token builtin">len</span><span class="token punctuation">(</span>rightsequence<span class="token punctuation">)</span><span class="token operator">></span><span class="token number">0</span><span class="token punctuation">:</span>self<span class="token punctuation">.</span>VerifySquenceOfBST<span class="token punctuation">(</span>rightsequence<span class="token punctuation">)</span><span class="token keyword">return</span> leftans <span class="token operator">and</span> rightans
if name==‘main’:
solution=Solution()
num=list(map(int,input().split(’ ')))
ans=solution.VerifySquenceOfBST(num)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
24.二叉树中和为某一值的路径
**题目:**输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)。
**思路:**利用递归的方法,计算加左子树和右子树之后的值,当参数较多是,可以将结果添加到函数变量之中。
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root:
return []
ans=[]
path=[]
self.dfs(root,expectNumber,ans,path)
ans.sort()
return ans
<span class="token keyword">def</span> <span class="token function">dfs</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>root<span class="token punctuation">,</span>target<span class="token punctuation">,</span>ans<span class="token punctuation">,</span>path<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> <span class="token operator">not</span> root<span class="token punctuation">:</span><span class="token keyword">return</span>path<span class="token punctuation">.</span>append<span class="token punctuation">(</span>root<span class="token punctuation">.</span>val<span class="token punctuation">)</span><span class="token keyword">if</span> root<span class="token punctuation">.</span>left <span class="token keyword">is</span> <span class="token boolean">None</span> <span class="token operator">and</span> root<span class="token punctuation">.</span>right <span class="token keyword">is</span> <span class="token boolean">None</span> <span class="token operator">and</span> target<span class="token operator">==</span>root<span class="token punctuation">.</span>val<span class="token punctuation">:</span>ans<span class="token punctuation">.</span>append<span class="token punctuation">(</span>path<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token keyword">if</span> root<span class="token punctuation">.</span>left<span class="token punctuation">:</span>self<span class="token punctuation">.</span>dfs<span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">,</span>target<span class="token operator">-</span>root<span class="token punctuation">.</span>val<span class="token punctuation">,</span>ans<span class="token punctuation">,</span>path<span class="token punctuation">)</span><span class="token keyword">if</span> root<span class="token punctuation">.</span>right<span class="token punctuation">:</span>self<span class="token punctuation">.</span>dfs<span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">,</span>target<span class="token operator">-</span>root<span class="token punctuation">.</span>val<span class="token punctuation">,</span>ans<span class="token punctuation">,</span>path<span class="token punctuation">)</span>path<span class="token punctuation">.</span>pop<span class="token punctuation">(</span><span class="token punctuation">)</span>
if name==‘main’:
A1=TreeNode(10)
A2=TreeNode(8)
A3=TreeNode(12)
A4=TreeNode(4)
A5=TreeNode(2)
A6=TreeNode(2)
A1<span class="token punctuation">.</span>left<span class="token operator">=</span>A2
A1<span class="token punctuation">.</span>right<span class="token operator">=</span>A3
A2<span class="token punctuation">.</span>left<span class="token operator">=</span>A4
A2<span class="token punctuation">.</span>right<span class="token operator">=</span>A5
A5<span class="token punctuation">.</span>left<span class="token operator">=</span>A6expectNumber<span class="token operator">=</span><span class="token number">22</span>
solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>FindPath<span class="token punctuation">(</span>A1<span class="token punctuation">,</span>expectNumber<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
25.复杂链表的复制
**题目:**输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。
**思路:**将大问题转变为小问题,每次都进行复制头部节点,然后进行递归,每次同样处理头部节点。
# -*- coding:utf-8 -*-
class RandomListNode:def __init__(self, x):self.label = xself.next = Noneself.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
# 复制头部节点
if pHead is None:
return None
newHead<span class="token operator">=</span>RandomListNode<span class="token punctuation">(</span>pHead<span class="token punctuation">.</span>label<span class="token punctuation">)</span>newHead<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>pHead<span class="token punctuation">.</span><span class="token builtin">next</span>newHead<span class="token punctuation">.</span>random<span class="token operator">=</span>pHead<span class="token punctuation">.</span>random<span class="token comment"># 递归其他节点</span>newHead<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>self<span class="token punctuation">.</span>Clone<span class="token punctuation">(</span>pHead<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token punctuation">)</span><span class="token keyword">return</span> newHead
if name==‘main’:
A1=RandomListNode(2)
A2=RandomListNode(3)
A3=RandomListNode(4)
A4=RandomListNode(5)
A5=RandomListNode(6)
A1<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A2
A1<span class="token punctuation">.</span>random<span class="token operator">=</span>A3A2<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A3
A2<span class="token punctuation">.</span>random<span class="token operator">=</span>A4A3<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A4
A3<span class="token punctuation">.</span>random<span class="token operator">=</span>A5A4<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>A5
A4<span class="token punctuation">.</span>random<span class="token operator">=</span>A3solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>Clone<span class="token punctuation">(</span>A1<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
26.二叉搜索树与双向列表
**题目:**输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
**思路:**递归将根结点和左子树的最右节点和右子树的最左节点进行连接起来。
# -*- coding:utf-8 -*- class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None class Solution:def Convert(self, pRootOfTree):# write code hereif pRootOfTree is None:return pRootOfTreeif pRootOfTree.left is None and pRootOfTree.right is None:return pRootOfTree
<span class="token comment">#处理左子树</span>self<span class="token punctuation">.</span>Convert<span class="token punctuation">(</span>pRootOfTree<span class="token punctuation">.</span>left<span class="token punctuation">)</span>left<span class="token operator">=</span>pRootOfTree<span class="token punctuation">.</span>left<span class="token keyword">if</span> left<span class="token punctuation">:</span><span class="token keyword">while</span> left<span class="token punctuation">.</span>right<span class="token punctuation">:</span>left<span class="token operator">=</span>left<span class="token punctuation">.</span>rightpRootOfTree<span class="token punctuation">.</span>left<span class="token punctuation">,</span>left<span class="token punctuation">.</span>right<span class="token operator">=</span>left<span class="token punctuation">,</span>pRootOfTree<span class="token comment">#处理右子树</span>self<span class="token punctuation">.</span>Convert<span class="token punctuation">(</span>pRootOfTree<span class="token punctuation">.</span>right<span class="token punctuation">)</span>right<span class="token operator">=</span>pRootOfTree<span class="token punctuation">.</span>right<span class="token keyword">if</span> right<span class="token punctuation">:</span><span class="token keyword">while</span> right<span class="token punctuation">.</span>left<span class="token punctuation">:</span>right<span class="token operator">=</span>right<span class="token punctuation">.</span>leftpRootOfTree<span class="token punctuation">.</span>right<span class="token punctuation">,</span>right<span class="token punctuation">.</span>left<span class="token operator">=</span>right<span class="token punctuation">,</span>pRootOfTree<span class="token keyword">while</span> pRootOfTree<span class="token punctuation">.</span>left<span class="token punctuation">:</span>pRootOfTree<span class="token operator">=</span>pRootOfTree<span class="token punctuation">.</span>left<span class="token keyword">return</span> pRootOfTree
if name==‘main’:
A1 = TreeNode(7)
A2 = TreeNode(5)
A3 = TreeNode(15)
A4 = TreeNode(2)
A5 = TreeNode(6)
A6 = TreeNode(8)
A7 = TreeNode(19)
A8 = TreeNode(24)
A1<span class="token punctuation">.</span>left<span class="token operator">=</span>A2
A1<span class="token punctuation">.</span>right<span class="token operator">=</span>A3
A2<span class="token punctuation">.</span>left<span class="token operator">=</span>A4
A2<span class="token punctuation">.</span>right<span class="token operator">=</span>A5
A3<span class="token punctuation">.</span>left<span class="token operator">=</span>A6
A3<span class="token punctuation">.</span>right<span class="token operator">=</span>A7
A7<span class="token punctuation">.</span>right<span class="token operator">=</span>A8solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
solution<span class="token punctuation">.</span>Convert<span class="token punctuation">(</span>A1<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
27.字符串的排列
**题目:**输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
**输入:**输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
**思路:**通过将第k位的字符提取到最前面,然后进行和后面的每个字符进行交换,得到所有结果集。
# -*- coding:utf-8 -*- class Solution:def Permutation(self, ss):# write code hereif not ss:return []res=[]self.helper(ss,res,'')return sorted(list(set(res)))
<span class="token keyword">def</span> <span class="token function">helper</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span>ss<span class="token punctuation">,</span>res<span class="token punctuation">,</span>path<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> <span class="token operator">not</span> ss<span class="token punctuation">:</span>res<span class="token punctuation">.</span>append<span class="token punctuation">(</span>path<span class="token punctuation">)</span><span class="token keyword">else</span><span class="token punctuation">:</span><span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token builtin">len</span><span class="token punctuation">(</span>ss<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>self<span class="token punctuation">.</span>helper<span class="token punctuation">(</span>ss<span class="token punctuation">[</span><span class="token punctuation">:</span>i<span class="token punctuation">]</span><span class="token operator">+</span>ss<span class="token punctuation">[</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">,</span>res<span class="token punctuation">,</span>path<span class="token operator">+</span>ss<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
if name==‘main’:
str=‘abbcDeefg’
str1=‘abbc’
solution=Solution()
ans=solution.Permutation(str1)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
28.数组中出现次数超过一般的数字
**题目:**数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0
**题解:**利用list列表来存放每个数出现的次数ans[numbers[i]]=ans[numbers[i]]+1。
# -*- coding:utf-8 -*-
class Solution:def MoreThanHalfNum_Solution(self, numbers):# write code herenumlen=len(numbers)halflen=numlen//2maxans=0ans=[0 for i in range(0,1000)]for i in range(0,len(numbers)):ans[numbers[i]]=ans[numbers[i]]+1if ans[numbers[i]]>maxans:maxans=numbers[i]ans.sort()ans.reverse()res=ans[0]if res>halflen:return maxanselse:return 0
if name==‘main’:
num=list(map(int,input().split(’,’)))
solution=Solution()
ans=solution.MoreThanHalfNum_Solution(num)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
29.最小的K个数
**题目:**输入n个整数,找出其中最小的K个数,例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
# -*- coding:utf-8 -*-
class Solution:def GetLeastNumbers_Solution(self, tinput, k):# write code hereif k>len(tinput):return []tinput.sort()return tinput[:k]
if name==‘main’:
num=list(map(int,input().split(’,’)))
k=int(input())
solution=Solution()
ans=solution.GetLeastNumbers_Solution(num,k)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
30.连续子数组的最大和
**题目:**HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)
# -*- coding:utf-8 -*-
class Solution:def FindGreatestSumOfSubArray(self, array):# write code heremaxsum,tempsum=array[0],array[0]for i in range(1,len(array)):if tempsum<0:tempsum=array[i]else:tempsum = tempsum + array[i]if tempsum>maxsum:maxsum=tempsumreturn maxsum
if name==‘main’:
array=list(map(int,input().split(’,’)))
solution=Solution()
ans=solution.FindGreatestSumOfSubArray(array)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
31.整数中1出现的次数
**题目:**求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
**思路:**对每个数字的每位进行分解,含有1则结果加1。
# -*- coding:utf-8 -*-
class Solution:def NumberOf1Between1AndN_Solution(self, n):# write code hereans=0for i in range(1,n+1):tempans=0while i!=0:eachnum=i%10i=i//10if eachnum==1:tempans=tempans+1ans=ans+tempansreturn ans
if name==‘main’:
n=130
solution=Solution()
ans=solution.NumberOf1Between1AndN_Solution(n)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
32.把数组排成最小的数
**题目:**输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
**思路:**将数组转换成字符串之后,进行两两比较字符串的大小,比如3,32的大小由332和323确定,即3+32和32+3确定。
# -*- coding:utf-8 -*-
class Solution:def PrintMinNumber(self, numbers):# write code hereif not numbers:return ""num = map(str, numbers)for i in range(0,len(numbers)):for j in range(i,len(numbers)):if int(str(numbers[i])+str(numbers[j]))>int(str(numbers[j])+str(numbers[i])):numbers[i],numbers[j]=numbers[j],numbers[i]ans=''for i in range(0,len(numbers)):ans=ans+str(numbers[i])return ans
if name==‘main’:
numbers=[3,32,321]
solution=Solution()
ans=solution.PrintMinNumber(numbers)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
33.丑数
**题目:**把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
**思路:**每一个丑数必然是由之前的某个丑数与2,3或5的乘积得到的,这样下一个丑数就用之前的丑数分别乘以2,3,5,找出这三这种最小的并且大于当前最大丑数的值,即为下一个要求的丑数。
# -*- coding:utf-8 -*-
class Solution:def GetUglyNumber_Solution(self, index):# write code hereif (index <= 0):return 0uglyList = [1]indexTwo = 0indexThree = 0indexFive = 0for i in range(index-1):newUgly = min(uglyList[indexTwo]*2, uglyList[indexThree]*3, uglyList[indexFive]*5)uglyList.append(newUgly)if (newUgly % 2 == 0):indexTwo += 1if (newUgly % 3 == 0):indexThree += 1if (newUgly % 5 == 0):indexFive += 1return uglyList[-1]
if name==‘main’:
solution=Solution()
index=200
ans=solution.GetUglyNumber_Solution(index)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
34.第一个只出现一次的字符
**题目:**在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1。
**思路:**找出所有出现一次的字符,然后进行遍历找到第一次出现字符的位置。
# -*- coding:utf-8 -*- class Solution:def FirstNotRepeatingChar(self, s):# write code hereif not s:return -1sset=set(s)dict={}for c in sset:dict[c]=0for i in range(0,len(s)):dict[s[i]]=dict[s[i]]+1onetime=[]for c in dict:if dict[c]==1:onetime.append(c)
<span class="token keyword">if</span> onetime <span class="token keyword">is</span> <span class="token boolean">None</span><span class="token punctuation">:</span><span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token keyword">else</span><span class="token punctuation">:</span>index<span class="token operator">=</span><span class="token number">0</span><span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token builtin">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> s<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token keyword">in</span> onetime<span class="token punctuation">:</span>index<span class="token operator">=</span>i<span class="token keyword">break</span><span class="token keyword">return</span> index
if name==‘main’:
s=‘abbddebbac’
solution=Solution()
ans=solution.FirstNotRepeatingChar(s)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
35.数组中的逆序对
**题目描述:**在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。
**输入描述:**题目保证输入的数组中没有的相同的数字。
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
示例1
输入 1,2,3,4,5,6,7,0
输出 7
# -*- coding:utf-8 -*- class Solution:def InversePairs(self, data):# write code hereglobal countcount = 0
<span class="token keyword">def</span> <span class="token function">A</span><span class="token punctuation">(</span>array<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">global</span> count<span class="token keyword">if</span> <span class="token builtin">len</span><span class="token punctuation">(</span>array<span class="token punctuation">)</span> <span class="token operator"><=</span> <span class="token number">1</span><span class="token punctuation">:</span><span class="token keyword">return</span> arrayk <span class="token operator">=</span> <span class="token builtin">int</span><span class="token punctuation">(</span><span class="token builtin">len</span><span class="token punctuation">(</span>array<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">)</span>left <span class="token operator">=</span> A<span class="token punctuation">(</span>array<span class="token punctuation">[</span><span class="token punctuation">:</span>k<span class="token punctuation">]</span><span class="token punctuation">)</span>right <span class="token operator">=</span> A<span class="token punctuation">(</span>array<span class="token punctuation">[</span>k<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span>l <span class="token operator">=</span> <span class="token number">0</span>r <span class="token operator">=</span> <span class="token number">0</span>result <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">while</span> l <span class="token operator"><</span> <span class="token builtin">len</span><span class="token punctuation">(</span>left<span class="token punctuation">)</span> <span class="token operator">and</span> r <span class="token operator"><</span> <span class="token builtin">len</span><span class="token punctuation">(</span>right<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token keyword">if</span> left<span class="token punctuation">[</span>l<span class="token punctuation">]</span> <span class="token operator"><</span> right<span class="token punctuation">[</span>r<span class="token punctuation">]</span><span class="token punctuation">:</span>result<span class="token punctuation">.</span>append<span class="token punctuation">(</span>left<span class="token punctuation">[</span>l<span class="token punctuation">]</span><span class="token punctuation">)</span>l <span class="token operator">+=</span> <span class="token number">1</span><span class="token keyword">else</span><span class="token punctuation">:</span>result<span class="token punctuation">.</span>append<span class="token punctuation">(</span>right<span class="token punctuation">[</span>r<span class="token punctuation">]</span><span class="token punctuation">)</span>r <span class="token operator">+=</span> <span class="token number">1</span>count <span class="token operator">+=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>left<span class="token punctuation">)</span> <span class="token operator">-</span> lresult <span class="token operator">+=</span> left<span class="token punctuation">[</span>l<span class="token punctuation">:</span><span class="token punctuation">]</span>result <span class="token operator">+=</span> right<span class="token punctuation">[</span>r<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token keyword">return</span> resultA<span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token keyword">return</span> count <span class="token operator">%</span> <span class="token number">1000000007</span>
if name==‘main’:
data=[1,2,3,4,5,6,7,0]
solution=Solution()
ans=solution.InversePairs(data)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
36.两个链表的第一个公共节点
**题目:**输入两个链表,找出它们的第一个公共结点。
# -*- coding:utf-8 -*-
class ListNode:def __init__(self, x):self.val = xself.next = None
class Solution:def FindFirstCommonNode(self, pHead1, pHead2):# write code herelist1 = []list2 = []node1 = pHead1node2 = pHead2while node1:list1.append(node1.val)node1 = node1.nextwhile node2:if node2.val in list1:return node2else:node2 = node2.next
if name==‘main’:
A1 = ListNode(1)
A2 = ListNode(2)
A3 = ListNode(3)
A1.next=A2
A2.next=A3
B4 <span class="token operator">=</span> ListNode<span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span>
B5 <span class="token operator">=</span> ListNode<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>
B4<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>B5C6<span class="token operator">=</span>ListNode<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span>
C7<span class="token operator">=</span>ListNode<span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">)</span>A3<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>C6
B5<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>C6
C6<span class="token punctuation">.</span><span class="token builtin">next</span><span class="token operator">=</span>C7solution<span class="token operator">=</span>Solution<span class="token punctuation">(</span><span class="token punctuation">)</span>
ans<span class="token operator">=</span>solution<span class="token punctuation">.</span>FindFirstCommonNode<span class="token punctuation">(</span>A1<span class="token punctuation">,</span>B4<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>ans<span class="token punctuation">.</span>val<span class="token punctuation">)</span>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
37.数字在排序数组中出现的次数
**题目:**统计一个数字在排序数组中出现的次数。
# -*- coding:utf-8 -*-
class Solution:def GetNumberOfK(self, data, k):# write code hereans=0for i in range(0,len(data)):if data[i]==k:ans=ans+1if data[i]>k:breakreturn ans
if name==‘main’:
data=[1,2,3,3,3,4,4,5]
k=3
solution=Solution()
ans=solution.GetNumberOfK(data,k)
print(ans)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
38.二叉树的深度
**题目:**输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
# -*- coding:utf-8 -*-
class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
left=self.TreeDepth(pRoot.left)
right=self.TreeDepth(pRoot.right)
print(left,right)
return max(left,right)+1
if name==‘main’: