文章目录
021 栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列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 here‘
if pushV ==[] or len(pushV) !=len(popV):
return None
stack=[]
index=0
for item in pushV:
stack.append(item)
while stack and stack[-1] ==popV[index]:
stack.pop()
index=index+1
if stack==[]:
return True
else:
return False
022 从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if root== None:
return []
support=[root]
ret=[]
while support:
tempnode=support[0]
ret.append(tempnode.val)
if tempnode.left:
support.append(tempnode.left)
if tempnode.right:
support.append(tempnode.right)
del support[0]
return ret
023二叉树的后序遍历
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if sequence ==[]:
return False
root =sequence[-1]
del sequence[-1]
index=None
for i in range(len(sequence)):
if index ==None and sequence[i]> root:
index=i
if index != None and sequence[i]< root:
return False
if sequence[:index] ==[]:
return True
else:
left=self.VerifySquenceOfBST(sequence[:index])
if sequence[index:]==[]:
return True
else:
right=self.VerifySquenceOfBST(sequence[index:])
return left and right
024 二叉树中和为某一值的路径
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import copy
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
if root == None:
return []
ret=[]
support=[root]
#路径
supportList=[[root.val]]
while support:
tempnode=support[0]
templu=supportList[0]
if tempnode.left == None and tempnode.right== None:
if sum(templu)==expectNumber:
ret.insert(0,templu)
if tempnode.left:
support.append(tempnode.left)
newarraylu=copy.copy(templu)
newarraylu.append(tempnode.left.val)
supportList.append(newarraylu)
if tempnode.right:
support.append(tempnode.right)
newarraylu=copy.copy(templu)
newarraylu.append(tempnode.right.val)
supportList.append(newarraylu)
del supportList[0]
del support[0]
return ret
# write code here
025 复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
import copy
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
#return copy.deepcopy(pHead)
if pHead ==None:
return None
pTemp=pHead
while pTemp:
node=RandomListNode(pTemp.label)
node.next=pTemp.next
pTemp.next=node
pTemp=node.next
#实现ramdom的指向
pTemp=pHead
while pTemp:
if pTemp.random:
pTemp.next.random=pTemp.random.next
pTemp=pTemp.next.next
pTemp=pHead
newtemp=pHead.next
newhead=pHead.next
while pTemp:
pTemp.next=pTemp.next.next
if newtemp.next:
newtemp.next=newtemp.next.next
newtemp=newtemp.next
pTemp=pTemp.next
return newhead
#断开链接
026 字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
# -*- coding:utf-8 -*-
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if len(ss)<=0:
return []
#return sorted(list(set(map(''.join,itertools.permutations(ss)))))
ret=[]
path=''
self.perm(ss,ret,path)
unik=list(set(ret))
return sorted(unik)
def perm(self,ss,res,path):
if ss == '':
res.append(path)
else:
for i in range(len(ss)):
self.perm(ss[:i]+ss[i+1:],res,path+ss[i])
027 数组中出现超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
#时间复杂度O(n) 空间复杂度O(n)
"""numcount=len(numbers)
numbermap={}
for item in numbers:
if item in numbermap:
numbermap[item]+=1
else:
numbermap[item]=1
if numbermap[item]>(numcount/2):
return item
return 0
"""
#想要空间复杂度是O(1),时间复杂度是O(n)
#抵消掉 把其他看作相同的数字
last=0
lastcount=0
for num in numbers:
if lastcount == 0:
last=num
if num ==last:
lastcount+=1
else:
lastcount-=1
if lastcount==0:
return 0
else:
lastcount=0
for num in numbers:
if num ==last:
lastcount+=1
if lastcount> (len(numbers)/2):
return last
else:
return 0
028 最小的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 here
#创建树
maxHeap=[]
if k<=0 or len(tinput)<k:
return []
def creatTree(num):
maxHeap.append(num)
currentIndex=len(maxHeap)-1
while currentIndex !=0:
parentIndex=(currentIndex-1)>>1
if maxHeap[parentIndex]<maxHeap[currentIndex]:
maxHeap[parentIndex],maxHeap[currentIndex]=maxHeap[currentIndex],maxHeap[parentIndex]
currentIndex=parentIndex
else:
break
#调整树
def adjustTree(num):
if num<maxHeap[0]:
maxHeap[0]=num
maxLength=len(maxHeap)
index=0
while index<maxLength:
leftIndex=index * 2 +1
rightIndex=index *2 +2
largeIndex=0
if rightIndex < maxLength:
if maxHeap[leftIndex]<maxHeap[rightIndex]:
largeIndex=rightIndex
else:
largeIndex=leftIndex
elif leftIndex < maxLength:
largeIndex=leftIndex
else:
break
if maxHeap[index]<maxHeap[largeIndex]:
maxHeap[index],maxHeap[largeIndex]=maxHeap[largeIndex],maxHeap[index]
index=largeIndex
else:
break
for i in range(len(tinput)):
if i < k:
creatTree(tinput[i])
else:
adjustTree(tinput[i])
maxHeap.sort()
return maxHeap
029 连续子数组的最大和
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
maxsum=None
tempSum=0
for i in array:
if maxsum ==None:
maxsum=i
if tempSum+i <i :
tempSum=i
else:
tempSum+=i
if maxsum<tempSum:
maxsum=tempSum
return maxsum
030 整数中1出现的次数
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
highValue=1
midValue=1
lowValue=1
percent=1
count=0
sumNum=0
while highValue !=0:
highValue=n//(percent*10)
midValue= (n//percent)%10
lowValue=n % percent
percent=percent*10
if midValue==0:
num=(highValue-1+1)*pow(10,count)
elif midValue>1:
num=(highValue+1)*pow(10,count)
else:
num=highValue *pow(10,count)+lowValue+1
count+=1
sumNum+=num
return sumNum
031 把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
def cmpNum(num1, num2):
str1 = str(num1) + str(num2)
str2 = str(num2) + str(num1)
if int(str1) < int(str2):
return True
else:
return False
def partition(array, left, right, cmp):
i = left - 1
for j in range(left, right):
smaller = False
if cmp:
smaller = cmpNum(array[j], array[right])
elif array[j] < array[right]:
smaller = True
if smaller:
array[j], array[i + 1] = array[i + 1], array[j]
i = i + 1
array[right], array[i + 1] = array[i + 1], array[right]
return i + 1
def quicksort(array, left=0, right=None,cmp=None):
arrayLen = len(array)
if arrayLen <= 1:
return
if right == None:
right = arrayLen - 1
if left < right:
povit = partition(array, left, right, cmp)
quicksort(array, left, povit - 1, cmp)
quicksort(array, povit + 1, right, cmp)
quicksort(numbers, cmp=cmpNum)
ret = ''
for item in numbers:
ret += str(item)
return ret
032 丑数
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index<1:
return 0
"""
def isUgly(num):
while num%2==0:
num=num//2
while num%3==0:
num=num//3
while num%5==0:
num=num//5
if num ==1 :
return True
else:
return False
count=0
num =1
while True:
if isUgly(num):
count+=1
if count==index:
return num
num+=1
"""
ret=[1]
towindex=0
threeindex=0
fiveindex=0
count=1
while count!=index:
minValue=min(2*ret[towindex],3*ret[threeindex],5*ret[fiveindex])
ret.append(minValue)
count+=1
if minValue== 2*ret[towindex] :
towindex+=1
if minValue== 3*ret[threeindex]:
threeindex+=1
if minValue== 5*ret[fiveindex]:
fiveindex+=1
return ret[count-1]
033第一个只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if len(s)<1:
return -1
retmap={}
for item in s:
if item in retmap:
retmap[item]+=1
else:
retmap[item]=1
for item in s:
if retmap[item]==1:
return s.index(item)
return -1
"""
if len(s)<0 or len(s)>10000:
return -1
for item in s:
if s.count(item)==1:
return s.index(item)
return -1
"""
034数组中的逆序对
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
# -*- coding:utf-8 -*-
import copy
count=0
class Solution:
def InversePairs(self, data):
# write code here
"""count=0
ccopyList=copy.copy(data)
ccopyList.sort()
for i in range(len(ccopyList)):
count+=data.index(ccopyList[i])
del data[ccopyList[i]]
return count%1000000007
"""
global count
def MergeSort(lists):
global count
if len(lists) <= 1:
return lists
num = int( len(lists)/2 )
left = MergeSort(lists[:num])
right = MergeSort(lists[num:])
r, l=0, 0
result=[]
while l<len(left) and r<len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
count += len(left)-l
result += right[r:]
result += left[l:]
return result
MergeSort(data)
return count%1000000007
035 两个链表的第一个公共结点
输入两个链表,找出它们的第一个公共结点。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
pTemp1=pHead1
pTemp2=pHead2
while pTemp1 and pTemp2:
if pTemp1==pTemp2:
return pTemp1
pTemp1=pTemp1.next
pTemp2=pTemp2.next
if pTemp1 :
k=0
while pTemp1:
pTemp1=pTemp1.next
k+=1
pTemp1=pHead1
for i in range(k):
pTemp1=pTemp1.next
pTemp2=pHead2
while pTemp1 != pTemp2:
pTemp1=pTemp1.next
pTemp2=pTemp2.next
return pTemp1
if pTemp2 :
k=0
while pTemp2:
pTemp2=pTemp2.next
k+=1
pTemp2=pHead2
for i in range(k):
pTemp2=pTemp2.next
pTemp1=pHead1
while pTemp1 != pTemp2:
pTemp1=pTemp1.next
pTemp2=pTemp2.next
return pTemp1
036 数字在排序数组中出现的次数
统计一个数字在排序数组中出现的次数。
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
#return data.count(k)
count=0
if not data or len(data)==0:
return 0
for item in data:
if item==k:
count+=1
return count
037 二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
left=self.TreeDepth(pRoot.left)+1
right=self.TreeDepth(pRoot.right)+1
return left if left >right else right
038 平衡二叉树
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
self.flag = True
self.tree_Iteration(pRoot)
return self.flag
def tree_Iteration(self, pRoot):
if not pRoot or self.flag==False:
return 0
left = self.tree_Iteration(pRoot.left)
right = self.tree_Iteration(pRoot.right)
if abs(left-right)>1:
self.flag = False
return left+1 if left>right else right+1
039 数组中只出现一次的数字
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
"""
mapList={}
for item in array:
if item in mapList:
mapList[item]+=1
else:
mapList[item]=1
ret=[]
for item in array:
if mapList[item]==1:
ret.append(item)
return ret
"""
if len(array) < 2:
return None
remain, index = 0, 1
for num in array:
remain = remain ^ num
while (remain & index) == 0:
index = index << 1
res1,res2 = 0,0
for num in array:
if (num & index) == 0:
res1 = res1^num
else:
res2 = res2^num
return [res1,res2]
040 和为S的连续整数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
# -*- coding:utf-8 -*-
import math
class Solution:
def FindContinuousSequence(self, tsum):
res = []
for div in range(2,int(math.sqrt(tsum*2))+1):
if (div%2==0 and tsum%div == div/2) or (div%2==1 and tsum%div == 0):
start = tsum//div - div//2 + 1 if div%2==0 else tsum//div - div//2
res.append(list(range(start, tsum//div + div//2 + 1)))
return sorted(res)
"""
def FindContinuousSequence(self, tsum):
# write code here
ret =[]
for div in range(int(math.sqrt(tsum*2))+1):
if (div //2==0 and tsum%div*2==div) or (div //2==1 and tsum%div==0):
start=tsum//div-div//2+1 if div%2==0 else tsum//div - div//2
ret.append(list(range(start,tsum//div + div//2 + 1)))
return sorted(ret)
"""