文章目录
- 【剑指offer-Python3】1 判断数组中是否含有某整数。
- 【剑指offer-Python3】2 替换字符串中的空格
- 【剑指offer-Python3】3 链表反转
- 【剑指offer-Python3】4 根据前序和中序遍历,重建二叉树
- 【剑指offer-Python3】5. 用两个栈来实现一个队列
- 【剑指offer-Python3】6. 旋转数组的最小值
- 【剑指offer-Python3】7. 斐波那契数列
- 【剑指offer-Python3】8. 青蛙跳阶
- 【剑指offer-Python3】9. 青蛙跳阶2
- 【剑指offer-Python3】10. 用小矩形覆盖大矩形
- 【剑指offer-Python3】11. 二进制中1的个数
- 【剑指offer-Python3】12. 求base的exponent次方
- 【剑指offer-Python3】13. 调整该数组中数字的顺序
- 【剑指offer-Python3】14. 链表的倒数第K个结点
- 【剑指offer-Python3】15. 反转链表后的新表头
- 【剑指offer-Python3】16. 合并两个链表
- 【剑指offer-Python3】17. 判断二叉树的子结构
- 【剑指offer-Python3】18. 二叉树的镜像
- 【剑指offer-Python3】19. 从外向里顺时针打印矩阵
- 【剑指offer-Python3】20. 寻找栈中所含最小元素
- 【剑指offer-Python3】21. 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序
- 【剑指offer-Python3】22. 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
- 【剑指offer-Python3】23. 判断数组是不是某二叉树的后序遍历
- 【剑指offer-Python3】24. 打印二叉树中结点值的和为输入整数的所有路径
- 【剑指offer-Python3】25. 复制链表的复制
- 【剑指offer-Python3】26. 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
- 【剑指offer-Python3】27. 输入一个字符串,按字典序打印出该字符串中字符的所有排列。
- 【剑指offer-Python3】28. 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
- 【剑指offer-Python3】29. 输入n个整数,找出其中最小的K个数。
- 【剑指offer-Python3】30 连续子数组的最大和
- 【剑指offer-Python3】31 整数中1出现的次数
- 【剑指offer-Python3】32. 把数组排成最小的数
- 【剑指offer-Python3】33. 丑数
- 【剑指offer-Python3】34. 第一个只出现一次的字符
- 【剑指offer-Python3】35. 数组中的逆序对
- 【剑指offer-Python3】36. 输入两个链表,找出它们的第一个公共结点。
- 【剑指offer-Python3】37. 统计一个数字在排序数组中出现的次数。
- 【剑指offer-Python3】38. 二叉树的深度
- 【剑指offer-Python3】39. 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
- 【剑指offer-Python3】40.找出只出现一次的数字
- 【剑指offer-Python3】41. 和为S的连续正数序列
- 【剑指offer-Python3】42. 和为s的两个数
- 【剑指offer-Python3】43. 左旋转字符串
- 【剑指offer-Python3】44. 旋转单词顺序列
- 【剑指offer-Python3】45. 扑克牌顺子
- 【剑指offer-Python3】46. 孩子们的游戏(圆圈中最后剩下的数)
- 【剑指offer-Python3】47. 求n个数字之和
- 【剑指offer-Python3】48. 不用加减乘除做加法
- 【剑指offer-Python3】49. 字符串转换为整数
- 【剑指offer-Python3】50. 数组中重复的数字
- 【剑指offer-Python3】51. 构建乘积数组
- 【剑指offer-Python3】52. 正则表达式匹配
- 【剑指offer-Python3】53. 表示数值的字符串
- 【剑指offer-Python3】54. 字符流中 第一个不重复的字符
- 【剑指offer-Python3】55. 链表中环的入口
- 【剑指offer-Python3】56. 删除链表中 重复的结点
- 【剑指offer-Python3】57. 二叉树的下一个结点
- 【剑指offer-Python3】58. 对称的二叉树
- 【剑指offer-Python3】59. 按之字顺序打印二叉树
- 【剑指offer-Python3】60. 把二叉树 打印成多行
- 【剑指offer-Python3】61. 序列化 二叉树
- 【剑指offer-Python3】62. 二叉搜索树的第K个结点
- 【剑指offer-Python3】63. 数据流中的中位数
- 【剑指offer-Python3】64. 滑动窗口的最大值
- 【剑指offer-Python3】65. 矩阵中的路径
- 【剑指offer-Python3】66. 机器人的运动范围
【剑指offer-Python3】1 判断数组中是否含有某整数。
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
find = False
m = len(array)
n = len(array[0])
if m > 0 and n >0:
i = 0
j = n-1
while(i<m and j>=0):
if array[i][j] == target:
find = True
break
elif array[i][j] > target:
j = j-1
elif array[i][j] < target:
i = i + 1
return find
【剑指offer-Python3】2 替换字符串中的空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
i = 0
n = len(s)
ssstr = []
for i in range(n):
if s[i].isspace():
ssstr.append('%20')
else:
ssstr.append(s[i])
ss = ''.join(ssstr)
return ss
【剑指offer-Python3】3 链表反转
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
# -*- 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
outList = []
head = listNode
while head != None:
outList.append(head.val)
head = head.next
outList.reverse()
return outList
【剑指offer-Python3】4 根据前序和中序遍历,重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
# -*- 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
root_rebuild = TreeNode(pre[0])
i = tin.index(pre[0])
root_rebuild.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i])
root_rebuild.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return root_rebuild
【剑指offer-Python3】5. 用两个栈来实现一个队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stackA = []
self.stackB = []
def push(self,node):
# write code here
self.stackA.append(node)
def pop(self):
# return xx
if self.stackB:
return self.stackB.pop()
elif not self.stackA:
return None
else:
while self.stackA:
self.stackB.append(self.stackA.pop())
return self.stackB.pop()
node = ["PSH1","PSH2","PSH3","POP","POP","PSH4","POP","PSH5","POP","POP"]
object1=Solution()
object1.push(node)
object1.pop()
['PSH1', 'PSH2', 'PSH3', 'POP', 'POP', 'PSH4', 'POP', 'PSH5', 'POP', 'POP']
【剑指offer-Python3】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 here
if len(rotateArray) == 0:
return 0
resultArray = []
minValue = rotateArray[0]
for i in range(len(rotateArray)):
if rotateArray[i] < minValue:
minIndex = i
minValue = rotateArray[i]
#print("minIndex: ",minIndex)
'''
for j in range(minIndex,len(rotateArray)):
print(rotateArray[j])
resultArray.append(rotateArray[j])
for j in range(0,minIndex):
resultArray.append(rotateArray[j])
'''
return minValue
#node = [3,4,5,1,2]
node = [6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170,9359,9719,9895,
9896,9913,9962,154,293,334,492,1323,1479,1539,1727,1870,1943,2383,2392,
2996,3282,3812,3903,4465,4605,4665,4772,4828,5142,
5437,5448,5668,5706,5725,6300,6335]
tmpClass=Solution()
print(tmpClass.minNumberInRotateArray(node))
154
【剑指offer-Python3】7. 斐波那契数列
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
(1,1,2,3,5,8,13,…)
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0 or n == 1:
return 1
while (n <= 39):
return self.Fibonacci(n-1)+self.Fibonacci(n-2)
def Fibonacci2(self, n):
# write code here
ss = []
if n == 0:
ss.append(0)
return 0
elif n == 1:
ss.append(1)
return 1
first = 0
second = 1
result = 0
for i in range(2,n+1):
result = first + second
first = second
second = result
ss.append(result)
print(result)
return result
tmpClass=Solution()
tmpClass.Fibonacci2(6)
8
8
【剑指offer-Python3】8. 青蛙跳阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
if number == 0:
return 0
elif number == 1:
return 1
elif number == 2:
return 2
first = 1
second = 2
result = 0
for i in range(3,number+1):
result = first + second
first = second
second = result
#ss.append(result)
return result
tmpClass=Solution()
tmpClass.jumpFloor(4)
5
5
【剑指offer-Python3】9. 青蛙跳阶2
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
if number == 0:
return 0
elif number == 1:
return 1
elif number == 2:
return 2
first = 2
result = 0
for i in range(3,number+1):
result = 2 * first
first = result
return result
【剑指offer-Python3】10. 用小矩形覆盖大矩形
我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
if number <= 0:
return 0
elif number <= 2:
return number
first = 1
second = 2
result = 0
for i in range(3,number+1):
result = first + second
first = second
second = result
#ss.append(result)
return result
【剑指offer-Python3】11. 二进制中1的个数
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
cnt = 0
if n<0:
n = n & 0xffffffff
while n:
cnt+=1
n = (n-1) & n
return cnt
#tmpClass=Solution()
tmpClass.NumberOf1(-10)
30
【剑指offer-Python3】12. 求base的exponent次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 1:
return base
first = base
result = 1
if exponent > 0:
for i in range(2, exponent+1):
result = first * base
first = result
elif exponent < 0:
for i in range(2, abs(exponent)+1):
result = first * base
first = result
result = 1.0 / result
else:
result = 1
return result
tmpClass=Solution()
ss = tmpClass.Power(2,-3)
print(ss)
0.125
【剑指offer-Python3】13. 调整该数组中数字的顺序
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
oddArray = []
evenArray = []
for i in range(len(array)):
if array[i] % 2 == 0:
evenArray.append(array[i])
else:
oddArray.append(array[i])
evenArray = oddArray + evenArray
return evenArray
arrayTest = [1,2,3,4,5,6,7,8,9]
tmpClass=Solution()
ss = tmpClass.reOrderArray(arrayTest)
print(ss)
[1, 3, 5, 7, 9, 2, 4, 6, 8]
【剑指offer-Python3】14. 链表的倒数第K个结点
输入一个链表,输出该链表中倒数第k个结点
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head == None or k < 0:
return None
count = 0
p = head
while p != None:
count += 1
p = p.next
if count < k:
return None
indexK = count - k + 1
index = 0
p = head
while p != None:
index += 1
if index == indexK:
return p
p = p.next
【剑指offer-Python3】15. 反转链表后的新表头
输入一个链表,反转链表后,输出新链表的表头
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None:
return None
p = pHead
last = None
while p != None and p.next != None:
tmp = p.next
p.next = last
last = p
p = tmp
return last
【剑指offer-Python3】16. 合并两个链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge11(self, pHead1, pHead2):
# write code here
if pHead1 == None and pHead2 == None:
return None
elif pHead1 != None and pHead2 == None:
return pHead1
elif pHead1 == None and pHead2 != None:
return pHead2
pResult = ListNode(0)
while pHead1 != None and pHead1 != None:
p1 = pHead1.val
p2 = pHead2.val
if p1 < p2:
pResult.next = ListNode(p1)
pHead1 = pHead1.next
else:
pResult.next = ListNode(p2)
pHead2 = pHead2.next
if pHead1:
pResult.next = pHead1
if pHead2:
pResult.next = pHead2
return pResult.next
def MergeRegression(self, pHead1, pHead2):
# write code here
if pHead1 == None and pHead2 == None:
return None
elif pHead1 != None and pHead2 == None:
return pHead1
elif pHead1 == None and pHead2 != None:
return pHead2
pResult = ListNode(0)
while pHead1 != None or pHead1 != None:
p1 = pHead1.val
p2 = pHead2.val
if p1 < p2:
pResult.val = pHead1.val
pResult.next = self.MergeRegression(pHead1.next, pHead2)
elif p1 == p2:
pResult.val = pHead1.val
pResult.val = pHead2.val
pResult.next = self.MergeRegression(pHead1.next, pHead2.next)
else:
pResult.val = pHead2.val
pResult.next = self.MergeRegression(pHead1, pHead2)
return pResult
def Merge(self, pHead1, pHead2):
# write code here
ret = ListNode(0)
print(ret)
tmp = ret
p1 = pHead1
p2 = pHead2
while(p1 and p2):
if p1.val<p2.val:
print(p1.val,p2.val)
tmp.next = ListNode(p1.val)
p1 = p1.next
else:
tmp.next = ListNode(p2.val)
p2 = p2.next
tmp = tmp.next
print(tmp.next.val)
'''
if p1:
tmp.next = p1
if p2:
tmp.next = p2
'''
#print(tmp.next.val)
return ret.next
def PrintList(self):
if self.length ==0:
return None
else:
p = self.head
while p.next:
print(p.data,'-->',end = '')
p = p.next
print(p.data)
if __name__ == '__main__':
solution = Solution()
pHead1 = ListNode([1, 2, 4, 7, 8])
pHead2 = ListNode([3,5,6,7,8,9])
#pHead1 = [1, 2, 4, 7, 8]
#pHead2 = [3,5,6,7,8,9]
ss = solution.Merge(pHead1, pHead2)
print(ss)
【剑指offer-Python3】17. 判断二叉树的子结构
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if pRoot1 == None or pRoot2 == None:
return False
resultFlag = False
if pRoot2.val == pRoot1.val:
resultFlag = self.isSubTree(pRoot1, pRoot2)
if resultFlag == False:
resultFlag = self.HasSubtree(pRoot1.left,pRoot2) | self.HasSubtree(pRoot1.right,pRoot2)
return resultFlag
def isSubTree(self, root1, root2):
if root2 == None:
return True
if root1 == None:
return False
if root1.val == root2.val:
return self.isSubTree(root1.left, root2.left) & self.isSubTree(root1.right, root2.right)
else:
return False
# 给定二叉树的前序遍历和中序遍历,获得该二叉树
def getBSTwithPreTin(self, pre, tin):
if len(pre)==0 | len(tin)==0:
return None
root = TreeNode(pre[0])
for order,item in enumerate(tin):
if root .val == item:
root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order])
root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:])
return root
if __name__ == '__main__':
solution = Solution()
preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8]
middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6]
treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
preorder_seq = [1, 2, 3]
middleorder_seq = [2, 1, 3]
treeRoot2 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
print(solution.HasSubtree(treeRoot1, treeRoot2))
True
【剑指offer-Python3】18. 二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if root == None:
return None
if root.left == None && root.right == None:
return None
self.subMirror(root.left, root.right)
return root
def subMirror(self, root1, root2):
if root1 != None and root2 != None:
tmp = root1.val
root1.val = root2.val
root2.val = tmp
self.subMirror(root1.left, root1.right)
self.subMirror(root2.left, root2.right)
def Mirror2(self, root):
if root == None:
return None
if root.left == None && root.right == None:
return None
TreeNode treeNode=root.left;
root.left=root.right;
root.right=treeNode;
if(root.left != None):
Mirror2(root.left)
if(root.right != None):
Mirror2(root.right)
return root
if __name__ == '__main__':
solution = Solution()
seq = [8,6,10,5,7,9,11]
treeRoot1 = solution.Mirror(seq)
print(treeRoot1)
File "<tokenize>", line 17
self.subMirror(root.left, root.right)
^
IndentationError: unindent does not match any outer indentation level
【剑指offer-Python3】19. 从外向里顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
m = len(matrix)
n = len(matrix[0])
resultMatrix = []
upper_i = 0
down_i = m-1
left_j = 0
right_j = n - 1
i = 0
j = 0
right_point = 1
down_point = 0
num = 0
while(num < m*n):
print(matrix[i][j])
resultMatrix.append(matrix[i][j])
if right_point == 1:
if j < right_j:
j += 1
else:
right_point = 0
down_point = 1
upper_i = upper_i + 1
i = i+1
elif down_point == 1:
if i < down_i:
i += 1
else:
down_point = 0
right_point = -1
right_j = right_j - 1
j -= 1
elif right_point == -1:
if j > left_j:
j -= 1
else:
right_point = 0
down_point = -1
down_i = down_i-1
i = i-1
elif down_point == -1:
if i > upper_i:
i = i - 1
else:
down_point = 0
right_point = 1
left_j = left_j + 1
j = j + 1
num += 1
return resultMatrix
if __name__ == '__main__':
solution = Solution()
seq = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print(seq)
treeRoot1 = solution.printMatrix(seq)
print(treeRoot1)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
1
2
3
4
8
12
16
15
14
13
9
5
6
7
11
10
[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
【剑指offer-Python3】20. 寻找栈中所含最小元素
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
用例:
[“PSH3”,“MIN”,“PSH4”,“MIN”,“PSH2”,“MIN”,“PSH3”,“MIN”,“POP”,“MIN”,“POP”,“MIN”,“POP”,“MIN”,“PSH0”,“MIN”]
对应输出应该为:
3,3,2,2,2,3,3,0
你的输出为:
object of type ‘bool’ has no len()
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.minstack = []
def push(self, node):
# write code here
self.stack.append(node)
if len(self.minstack)== 0 or self.minstack[-1][0] > node:
self.minstack.append((node, 1))
elif self.minstack[-1][0] == node:
self.minstack[-1] = (node, self.minstack[-1][1] +1)
def pop(self):
# write code here
tmp = self.stack[-1]
self.stack = self.stack[0:len(self.stack)-1]
if tmp == self.minstack[-1][0]:
if self.minstack[-1][1] == 1:
self.minstack[-1][0].remove(self.minstack[-1])
else:
self.minstack[-1] = (tmp, self.minstack[-1][1] -1)
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.minstack[-1][0]
node = ["PSH3","MIN","PSH4","MIN","PSH2","MIN","PSH3","MIN","POP","MIN","POP","MIN","POP","MIN","PSH0","MIN"]
solution = Solution()
solution.push(node)
solution.pop()
【剑指offer-Python3】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 here
stack = []
print(pushV)
while(popV):
if pushV and pushV[0] == popV[0]:
pushV.pop(0)
popV.pop(0)
elif stack and stack[-1] == popV[0]:
stack.pop()
popV.pop(0)
elif pushV:
stack.append(pushV.pop(0))
else:
return False
return True
if __name__ == '__main__':
solution = Solution()
pushV1 = [1,2,3,4,5]
popV1 = [4,5,3,2,1]
result = solution.IsPopOrder(pushV1,popV1)
print(result)
[1, 2, 3, 4, 5]
True
【剑指offer-Python3】22. 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
用例:
{10,6,14,4,8,12,16}
对应输出应该为:
[10,6,14,4,8,12,16]
你的输出为:
[10]
# -*- 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
result = []
if root == None:
return result
if root.left == None and root.right == None:
return result
result.append(root.val)
self.PrintFromTopToBottom(root.left)
self.PrintFromTopToBottom(root.right)
return result
【剑指offer-Python3】23. 判断数组是不是某二叉树的后序遍历
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) == 0:
return False
root = sequence[-1]
i=0
for node in sequence[:-1]:
if node > root:
break
i += 1
for node in sequence[i:-1]:
if node < root:
return False
left = True
if i > 1:
left = self.VerifySquenceOfBST(sequence[:-1])
right = True
if i < len(sequence)-1 and left:
righr = self.VerifySquenceOfBST(sequence[i+1:-1])
return left and right
【剑指offer-Python3】24. 打印二叉树中结点值的和为输入整数的所有路径
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
result = []
if not root:
return result
if not root.left and not root.right and root.val == expectNumber:
result.append([root.val])
return result
else:
left = self.FindPath(root.left, expectNumber - root.val)
right = self.FindPath(root.right, expectNumber - root.val)
for item in left+right:
result.append([root.val]+item)
return result
【剑指offer-Python3】25. 复制链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
# -*- coding:utf-8 -*-
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return pHead
cloNode = pHead
while cloNode:
node = RandomListNode(cloNode.label)
node.next = cloNode.next
cloNode.next = node
cloNode = node.next
cloNode = pHead
while cloNode:
node = cloNode.next
if cloNode.random:
node.random = cloNode.random.next
cloNode = node.next
cloNode = pHead
pHead = pHead.next
while cloNode.next:
node = cloNode.next
cloNode.next = node.next
cloNode = node
return pHead
【剑指offer-Python3】26. 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = None
self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return (None,None)
#递归构造出左右子树的双向列表
(l_1,r_1) = self.Convert(pRootOfTree.left)
if l_1:
left_most = pRootOfTree
else:
left_most = l_1
(l_2,r_2) = self.Convert(pRootOfTree.right)
if l_2:
right_most = pRootOfTree
else:
right_most = r_2
#将整理好的左右子树和root连接
pRootOfTree.left = r_1
if r_1:
r_1.right = pRootOfTree
pRootOfTree.right = l_2
if l_2:
l_2.left = pRootOfTree
return (left_most, right_most)
def create_a_tree(self):
node_4 = TreeNode(4)
node_8 = TreeNode(8)
node_6 = TreeNode(6, node_4, node_8)
node_12 = TreeNode(12)
node_16 = TreeNode(16)
node_14 = TreeNode(14, node_12, node_16)
node_10 = TreeNode(10, node_6, node_14)
return node_10
def print_a_tree(self,root):
if root is None:
return
self.print_a_tree(root.left)
print (root.val, ' ',)
self.print_a_tree(root.right)
def print_a_linked_list(self,head):
print ('linked_list:')
while head is not None:
print (head.val, ' ',)
head = head.right
print ('')
if __name__ == '__main__':
solution = Solution()
tree_1 = solution.create_a_tree()
solution.print_a_tree(tree_1)
(left_most, right_most) = solution.Convert(tree_1)
solution.print_a_linked_list(left_most)
pass
10
linked_list:
【剑指offer-Python3】27. 输入一个字符串,按字典序打印出该字符串中字符的所有排列。
例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
char_list = list(ss)
n = len(ss)
if n > 9:
return False
if n == 0:
return []
if n == 1:
return char_list
result = []
for i in range(n):
if i>0 and char_list[i] == char_list[i-1]:
continue
tmp = self.Permutation(''.join(char_list[:i]) + ''.join(char_list[i+1:]))
for item in tmp:
result.append(char_list[i]+item)
return result
【剑指offer-Python3】28. 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为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
n = len(numbers)
if n == 0:
return 0
threValue = n/2
numbers.sort()
#print(numbers)
count = 1
res = numbers[0]
maxCount = 0
maxRes = numbers[0]
for i in range(1, n):
if count == 0:
res = numbers[i]
count = 1
elif numbers[i] == res:
count = count + 1
if count > maxCount:
maxCount = count
maxRes = numbers[i]
elif numbers[i] != res:
count = count - 1
#print(maxRes,maxCount)
result_counts = 0
for j in range(n):
if numbers[j] == maxRes:
result_counts = result_counts + 1
if result_counts > threValue:
return res
else:
return 0
if __name__ == '__main__':
#arr = [int(i) for i in input().split()]
solution = Solution()
arr = [1, 2, 3, 2, 5, 2, 2, 2 ]
print(solution.MoreThanHalfNum_Solution(arr))
[1, 2, 2, 2, 2, 2, 3, 5]
2 4
2
【剑指offer-Python3】29. 输入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
n = len(tinput)
if k >= n:
return tinput
tinput.sort()
print(tinput)
result= []
for i in range(k):
result.append(tinput[i])
return result
if __name__ == '__main__':
solution = Solution()
arr = [4,5,1,6,2,7,3,8]
print(solution.GetLeastNumbers_Solution(arr, 4))
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4]
【剑指offer-Python3】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 here
if len(array) == 0:
return 0
maxSum = 0
maxArray = []
for i in range(len(array)):
tmpSum = array[i]
tmparr = []
tmparr.append(array[i])
for j in range(i+1, len(array)):
tmpSum += array[j]
tmparr.append(array[j])
if tmpSum > maxSum:
maxSum = tmpSum
maxArray = tmparr
#print(maxSum, maxArray)
return maxSum
if __name__ == '__main__':
solution = Solution()
arr = [4,5,1,6,2,7,3,8]
print(solution.FindGreatestSumOfSubArray(arr))
[4, 5]
[4, 5, 1]
[4, 5, 1, 6]
[4, 5, 1, 6, 2]
[4, 5, 1, 6, 2, 7]
[4, 5, 1, 6, 2, 7, 3]
[4, 5, 1, 6, 2, 7, 3, 8]
[5, 1]
[5, 1, 6]
[5, 1, 6, 2]
[5, 1, 6, 2, 7]
[5, 1, 6, 2, 7, 3]
[5, 1, 6, 2, 7, 3, 8]
[1, 6]
[1, 6, 2]
[1, 6, 2, 7]
[1, 6, 2, 7, 3]
[1, 6, 2, 7, 3, 8]
[6, 2]
[6, 2, 7]
[6, 2, 7, 3]
[6, 2, 7, 3, 8]
[2, 7]
[2, 7, 3]
[2, 7, 3, 8]
[7, 3]
[7, 3, 8]
[3, 8]
36 [4, 5, 1, 6, 2, 7, 3, 8]
36
【剑指offer-Python3】31 整数中1出现的次数
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
由此推测,对于1-9,10-99,100-999,每个n位数中包含1的个数公式为:
f(1) = 1
f(2) = 9 * f(1) + 10 ** 1
f(3) = 9 * f(2) + 10 ** 2
f(n) = 9 * f(n-1) + 10 ** (n-1)
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if n < 10 and n >= 1:
return 1
else:
return 0
digit = self.get_digits(n) #数字的位数
low_nums = self.get_1_each_degits(digit-1) #此高位
high = int(str[n][0]) #最高位
low = n - high * 10 ** (digit-1)
if high == 1:
high_nums = low+1
all_nums = high_nums
else:
high_nums = 10 ** (digit -1)
all_nums = high_nums + low_nums*(high-1)
return low_nums+all_nums+get_1_each_degits(low)
def get_digits(self,n):
ret = 0
while n:
ret += 1
n = n/10
return ret
def get_1_each_degits(n):
if n <= 0:
return 0
if n == 1:
return 1
current = 9 * self.get_1_each_degits(n-1) + 10 **(n-1)
return self.get_1_each_degits(n-1) + current
if __name__ == '__main__':
solution = Solution()
n = 15
print(solution.NumberOf1Between1AndN_Solution(n))
【剑指offer-Python3】32. 把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
def cmp(self, a, b):
'''定义比较函数'''
ab = int(a+b)
ba = int(b+a)
print(ab,ba)
return 1 if ab > ba else -1
def PrintMinNumber(self, numbers):
string = [str(num) for num in numbers]
string.sort(self.cmp, reverse=True)
return ''.join(string)
if __name__ == '__main__':
solution = Solution()
node = [3,32,321]
print(solution.NumberOf1Between1AndN_Solution(node))
【剑指offer-Python3】33. 丑数
把只包含质因子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 == 0:
return 0
uglyNum = [1]
i=1
t2 = m2 = 0
t3 = m3 = 0
t5 = m5 = 0
while i < index:
for x in range(t2, len(uglyNum)):
m2 = uglyNum[x] * 2
if m2 > uglyNum[-1]:
t2 = x
break
for x in range(t3, len(uglyNum)):
m3 = uglyNum[x] * 3
if m3 > uglyNum[-1]:
t3 = x
break
for x in range(t5, len(uglyNum)):
m5 = uglyNum[x] * 5
if m5 > uglyNum[-1]:
t5 = x
break
uglyNum.append(min(m2,m3,m5))
i += 1
print(uglyNum)
return uglyNum[-1]
【剑指offer-Python3】34. 第一个只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s or len(s) > 10000:
return -1
else:
for i in s:
if s.count(i) == 1:
return s.index(i)
【剑指offer-Python3】35. 数组中的逆序对
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入:
1,2,3,4,5,6,7,0
输出:7
运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
case通过率为50.00%
# -*- coding:utf-8 -*-
class Solution:
def InversePairs(self, data):
if not data:
return False
if len(data) == 1:
return 0
# write code here
sortedData = sorted(data)
count = 0
for i in sortedData:
pos = data.index(i)
count += pos
data.pop(pos)
return count
def quick_sort(self,data):
if len(data) < 2:
return data
left = self.quick_sort([i for i in data[1:] if i <= data[0]])
left = self.quick_sort([j for j in data[1:] if j > data[0]])
return left + [data[0]] + right
S=Solution()
#array1=[1,2,3,2,1]
array1 = [5,4,3,2]
print ('inverse pairs of array1:',S.InversePairs(array1))
inverse pairs of array1: 6
【剑指offer-Python3】36. 输入两个链表,找出它们的第一个公共结点。
公共结点的意思是相同的点,不仅值相同,next也相同,那么同理公共结点后面的点也是不仅值相同,而且next也相同,这样的话,就可以把两条链条看成Y字型了,某一个结点后面的点全部一样。举例,1->2->3->4->6和2->3->5->4->6,4就是他们的第一个公共结点。
# -*- 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
stack1 = []
stack2 = []
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
node1 = None
while stack1 and stack2 and stack1[-1] == stack2[-1]:
node = stack1.pop()
stack2.pop()
return node1
【剑指offer-Python3】37. 统计一个数字在排序数组中出现的次数。
答案错误:您提交的程序没有通过所有的测试用例
case通过率为0.00%
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if not data or len(data) == 0:
return 0
left = 0
right = len(data)
leftk = self.getleftK(data, k, left, right)
rightk = self.getrightK(data, k, left, right)
return rightk - leftk
def getleftK(self, data, k, left, right):
while left < right:
middle = (left + right) // 2
if data[middle] < k:
left = middle + 1
else:
right = middle - 1
return left
def getrightK(self, data, k, left, right):
while left < right:
middle = (int)(left + right) // 2
if data[middle] <= k:
left = middle + 1
else:
right = middle - 1
return right
S=Solution()
array1=[1,2,2,3,4,4,4,4,4,4,4,5,6,7,7,7,7,7,7,8,9]
#array1 = [5,4,3,2]
print ('统计一个数字在排序数组中出现的次数:',S.GetNumberOfK(array1, 4))
leftk1, rightk1 3
leftk2, rightk2 10
统计一个数字在排序数组中出现的次数: 7
【剑指offer-Python3】38. 二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
# -*- 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
if pRoot.val and pRoot.left == None and pRoot.right == None:
return 1
l_depth = self.TreeDepth(pRoot.left)
r_depth = self.TreeDepth(pRoot.right)
return max(l_depth,r_depth)+1
【剑指offer-Python3】39. 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
答案错误:您提交的程序没有通过所有的测试用例
case通过率为28.57%
# -*- 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):
# write code here
if pRoot == None:
return True
if (pRoot.left and pRoot.right == None) or (pRoot.left==None and pRoot.right):
return False
left = self.IsBalanced_Solution(pRoot.left)
right = self.IsBalanced_Solution(pRoot.right)
if abs(left - right) > 1:
return False
return True
【剑指offer-Python3】40.找出只出现一次的数字
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
result = []
array = sorted(array)
flagSame = False
if array[0] != array[1]:
result.append(array[0])
if array[len(array)-1] != array[len(array)-2]:
result.append(array[len(array)-1])
for i in range(1,len(array)-1):
if array[i] != array[i+1] and array[i] != array[i-1]:
result.append(array[i])
#print(result)
return result
S=Solution()
array1=[1,2,2,5,4,4,4,4,4,4,4,5,6,7,7,7,7,7,7,8,6]
#array1 = [5,4,3,2]
print ('result:',S.FindNumsAppearOnce(array1))
result: [1, 8]
【剑指offer-Python3】41. 和为S的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
答案错误:您提交的程序没有通过所有的测试用例
case通过率为0.00%
# -*- coding:utf-8 -*-
class Solution:
def FindContinuousSequence(self, tsum):
# write code here
if tsum == 1:
return [[1]]
if tsum == 2:
return [[1,1],[2]]
resultArr = []
low = 1
high = 2
while(high > low):
addArray = []
sum1 = (low+high) * (high-low+1) /2
#print(sum1, tsum,low,high)
if sum1 < tsum:
high += 1
elif sum1 > tsum:
low += 1
else:
addArray = self.addresult(low, high)
resultArr.append(addArray)
#print(resultArr)
low += 1
return resultArr
def addresult(self, low,high):
addArray = []
for i in range(low, high):
addArray.append(i)
return addArray
S=Solution()
array1=100
#array1 = [5,4,3,2]
print ('result:',S.FindContinuousSequence(array1))
result: [[9, 10, 11, 12, 13, 14, 15], [18, 19, 20, 21]]
【剑指offer-Python3】42. 和为s的两个数
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
答案错误:您提交的程序没有通过所有的测试用例
case通过率为40.00%
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
array = sorted(array)
print(array)
if len(array) == 0:
return None
resultArr = []
for i in range(len(array)):
for j in range(i+1, len(array)):
sum1 = array[i] + array[j]
tmparray = []
#print(sum1, tsum, array[i] , array[j])
if sum1 > tsum:
break
elif sum1 < tsum:
j += 1
else:
tmparray =[array[i], array[j]]
resultArr.append(tmparray)
break
nl = len(resultArr)
print(resultArr)
if nl > 0:
minMul = resultArr[0][0] * resultArr[0][1]
minArray = resultArr[0]
for i in range(nl):
tmpMul = resultArr[i][0] * resultArr[i][1]
if tmpMul < minMul:
minMul = tmpMul
minArray = resultArr[i]
return minArray
else:
return None
S=Solution()
array1=[1,2,2,5,4,3,4,4,4,4,4,5,6,7,7,9,7,7,7,8,6]
#array1 = [5,4,3,2]
print ('result:',S.FindNumbersWithSum(array1,20))
[1, 2, 2, 3, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8, 9]
[]
result: None
【剑指offer-Python3】43. 左旋转字符串
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if len(s) == 0:
return ""
if n >= len(s):
return s
else:
s_left = s[:n]
s_right = s[n:len(s)]
print( s_left,s_right)
return s_right+ s_left
S=Solution()
array1='abcXYZdef'
#array1 = [5,4,3,2]
print ('result:',S.LeftRotateString(array1,3))
abc XYZdef
result: XYZdefabc
【剑指offer-Python3】44. 旋转单词顺序列
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if not s:
return None
tmp_s = s
l_s = tmp_s.split('.')[0]
r_s = tmp_s.split('.')[-1]
l_s_tmp = l_s.split(' ')
l_s = l_s_tmp[::-1]
r_s_tmp = r_s.split(' ')
r_s = r_s_tmp[::-1]
result = r_s + l_s
str = ' '.join(result)
str += '.'
print(l_s, r_s,result,str)
return str
def reverse(self,str_list,start,end):
while start < end:
str_list[start], str_list[end]= str_list[end], str_list[start]
start+=1
end-=1
def ReverseSentence2(self, s):
str=s
str_list=list(str)#将str字符串转化成list
i=0
while i<len(str_list):
if str_list[i]!=' ':
start=i
end=i+1
while (end<len(str_list)) and str_list[end]!=' ' :#小心越界呀~
end+=1
self.reverse(str_list,start,(end-1))
i=end
else:
i+=1
str_list.reverse()
print(str_list)
return (' '.join(str_list))
S=Solution()
array1='student. a am I'
print ('result:',S.ReverseSentence2(array1))
['I', ' ', 'a', 'm', ' ', 'a', ' ', 's', 't', 'u', 'd', 'e', 'n', 't', '.']
result: I a m a s t u d e n t .
【剑指offer-Python3】45. 扑克牌顺子
LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)…他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子…LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
# -*- coding:utf-8 -*-
class Solution:
def IsContinuous(self, numbers):
# write code here
#numbers : 抽取的5张牌
if len(numbers) == 0:
return False
numbers.sort()
num_of_zero = numbers.count(0)
num_of_gap = 0
small = num_of_zero
big = small + 1
while big < len(numbers):
if numbers[small] == numbers[big]:
return False
num_of_gap += numbers[big] - numbers[small] - 1
small += 1
big += 1
if num_of_gap > num_of_zero:
return False
else:
return True
【剑指offer-Python3】46. 孩子们的游戏(圆圈中最后剩下的数)
每年六一儿童节,学校都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为学校的校长,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
# -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if n < 0 or m < 1:
return -1
last = 0
for i in range(2, n+1):
last = (last+m) % i
return last
【剑指offer-Python3】47. 求n个数字之和
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
sum = (n**2 + n) >> 1
return sum
【剑指offer-Python3】48. 不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
# -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
while(num2):
num1,num2 = (num1^num2) & 0xFFFFFFFF, ((num1&num2)<<1) & 0xFFFFFFFF
if num1 <= 0x7FFFFFFF:
return num1
else:
return ~(num1^0xFFFFFFFF)
【剑指offer-Python3】49. 字符串转换为整数
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
bitweigh = 1
result = 0
if len(s) == 0:
return result
if len(s) == 1 and not s[0].isdigit():
return 0
for i in range(len(s)-1, -1, -1):
if s[i].isdigit():
result += (ord(s[i]) - ord('0')) * bitweigh
bitweigh *= 10
continue
else:
if i == 0 and (s[i] == '+' or s[i] == '-'):
continue
else:
return 0
if s[0] is '-':
return -1 * result
else:
return result
【剑指offer-Python3】50. 数组中重复的数字
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
用例:
[2,1,3,1,4]
对应输出应该为:
“true,1”
你的输出为:
“true,-1”
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if len(numbers) == 0:
return []
else:
tmp = []
for i in range(len(numbers)):
if len(tmp) > 0:
for j in range(len(tmp)):
if tmp[j] == numbers[i]:
duplication.append(numbers[i])
return True
break
tmp.append(numbers[i])
print(duplication)
return False
S=Solution()
#array1=[2,3,1,0,4,5,0,4,3,2]
array1 = [2,1,3,1,4]
dup = []
print ('result:',S.duplicate(array1,dup))
result: True
【剑指offer-Python3】51. 构建乘积数组
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。
# -*- coding:utf-8 -*-
class Solution:
def multiply(self, A):
# write code here
if len(A) == 0:
return []
n = len(A)
B = [None] * n
B[0] = 1
print(B)
for i in range(1, n):
B[i] = B[i-1] * A[i-1]
tmp = 1
for i in range(n-2, -1, -1):
tmp *= A[i+1]
B[i] *= tmp
return B
S=Solution()
array1=[1,2,3,4,5,6,7,8]
print ('result:',S.multiply(array1))
[1, None, None, None, None, None, None, None]
result: [40320, 20160, 13440, 10080, 8064, 6720, 5760, 5040]
【剑指offer-Python3】52. 正则表达式匹配
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
# -*- coding:utf-8 -*-
class Solution:
# s, pattern都是字符串
def match(self, s, pattern):
# write code here
if len(s) == 0 and len(pattern) == 0:
return True
if len(s) > 0 and len(pattern) == 0:
return False
if len(pattern) > 1 and pattern[1] == '*':
if len(s) > 0 and (s[0] == pattern[0] or pattern[0] == '.'):
return self.match(s, pattern[2:]) or self.match(s[1:], pattern)
else:
return self.match(s, pattern[2:]) #第一个字符不匹配,相当于忽略x*
if len(s) > 0 and (s[0] == pattern[0] or pattern[0] == '.'):
return self.match(s[1:], pattern[1:])
else:
return False
S=Solution()
array1="abbbba"
str2 = "ab*a"
print ('result:',S.match(array1,str2))
result: True
【剑指offer-Python3】53. 表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
答案错误:您提交的程序没有通过所有的测试用例
case通过率为73.33%
用例:
“1+23”
对应输出应该为:
false
你的输出为:
true
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if len(s) == 0:
return False
isE = False
isdecimal = False
issign = False
for i in range(len(s)):
if s[i] == 'e' or s[i] == 'E':
if isE or i == len(s)-1 :
return False
isE = True
elif s[i] == '.':
if isE or isdecimal:
return False
isdecimal = True
elif s[i] == '+' or s[i] == '-':
if issign and i>0 and s[i-1] != 'e' and s[i-1] != 'E':
return False
issign = True
elif s[i] <'0' or s[i] > '9':
return False
return True
S=Solution()
array1='-1E-16'#"12e+4.3" # "+100"
print ('result:',S.isNumeric(array1))
result: True
【剑指offer-Python3】54. 字符流中 第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
# -*- coding:utf-8 -*-
class Solution:
# 返回对应char
def __init__(self):
self.charList = []
def FirstAppearingOnce(self):
print(self.charList)
for i in self.charList:
if self.charList.count(i) == 1:
print(i)
return i
return '#'
# write code here
def Insert(self, char):
# write code here
self.charList.append(char)
S=Solution()
array1='google'
print ('result:',S.Insert('g'))
print ('result:',S.Insert('g'))
print ('result:',S.Insert('o'))
print ('result:',S.Insert('o'))
print ('result:',S.Insert('g'))
print ('result:',S.Insert('l'))
print ('result:',S.FirstAppearingOnce())
result: None
result: None
result: None
result: None
result: None
result: None
['g', 'g', 'o', 'o', 'g', 'l']
l
result: l
【剑指offer-Python3】55. 链表中环的入口
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
slow = pHead
fast = pHead
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if not fast or not fast.next:
return None
fast = pHead
while fast != slow:
fast = fast.next
slow = slow.next
return fast
【剑指offer-Python3】56. 删除链表中 重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
first = ListNode(-1)
first.next = pHead
last = first
while pHead and pHead.next:
if pHead.val == pHead.next.val:
val = pHead.val
while pHead and val == pHead.val:
pHead = pHead.next
last.next = pHead
else:
last = pHead
pHead = pHead.next
return first.next
def getNewChart(self,list):
if list:
node = ListNode(list.pop(0))
node.next = self.getNewChart(list)
return node
if __name__ == '__main__':
list = [1,1,1,2,3,3,4]
listNode = Solution().getNewChart(list)
head = Solution().deleteDuplication(listNode)
while head:
print(head.val, end=" ")
head = head.next
2 4
【剑指offer-Python3】57. 二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
case通过率为37.50%
用例:
{8,6,10,5,7,9,11},11
对应输出应该为:
“null”
你的输出为:
8
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
return None
if pNode.right:
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
else:
while pNode.next:
if pNode == pNode.next.left:
return pNode.next
pNode = pNode.next
return pNode
【剑指offer-Python3】58. 对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
用例:
{8,6,6,5,7,7,5}
对应输出应该为:
true
你的输出为:
false
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.recursiveTree(pRoot.left, pRoot.right)
def recursiveTree(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val == right.val:
return self.recursiveTree(left.left, left.right) and \
self.recursiveTree(right.left, right.right)
return False
【剑指offer-Python3】59. 按之字顺序打印二叉树
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
内存超限
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Print(self, pRoot):
# write code here
if not pRoot:
return None
result = []
curLayerNodes = [pRoot]
is_even_layer = False
while curLayerNodes:
curlayerValues = []
nextlayerValues = []
is_even_layer = not is_even_layer
for node in curLayerNodes:
curlayerValues.append(node.val)
if node.left:
curlayerValues.append(node.left)
if node.right:
curlayerValues.append(node.right)
#curlayerValues = nextlayerValues
nextlayerValues = curlayerValues
if is_even_layer:
result.append(curlayerValues[::-1])
else:
result.append(curlayerValues)
return result
【剑指offer-Python3】60. 把二叉树 打印成多行
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot:
return None
result = []
curLayerNodes = [pRoot]
is_even_layer = False
while curLayerNodes:
curlayerValues = []
nextlayerValues = []
for node in curLayerNodes:
curlayerValues.append(node.val)
if node.left:
curlayerValues.append(node.left)
if node.right:
curlayerValues.append(node.right)
#curlayerValues = nextlayerValues
nextlayerValues = curlayerValues
result.append(curlayerValues)
return result
【剑指offer-Python3】61. 序列化 二叉树
请实现两个函数,分别用来序列化和反序列化二叉树
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
# write code here
if not root:
return '#'
return str(root.val)+ ',' + self.Serialize(root.left)+ ',' + self.Serialize(root.right)
def Deserialize(self, s):
# write code here
list0 = s.split(',')
return self.deserializeTree(list0)
def deserializeTree(self,list):
if len(list) <= 0:
return None
val = list.pop(0)
root = None
if val != '#':
root = TreeNode(int(val))
root.left = self.deserializeTree(list)
root.right = self.deserializeTree(list)
return root
File "<ipython-input-6-54ad0dae9977>", line 17
return self.
^
SyntaxError: invalid syntax
【剑指offer-Python3】62. 二叉搜索树的第K个结点
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
为什么 [ 按结点数值大小顺序第三个结点的值为4 ] ?
题中没有直接传达的一个信息是:给定一颗平衡二叉树,按照中序遍历的顺序,获得其第k大的节点。
基于以上信息开始求解,会发现这几乎就是一道中序遍历的题,不同之处仅仅在于:中序遍历返回二叉树中序遍历后所有节点的值的列表,而这道题返回中序遍历过程中填入列表的第k个节点。我们当然可以先对平衡二叉树进行中序遍历,在返回的列表中找到第k个节点;但很显然还有更直接的方式,即中序遍历到需要的位置后立即返回,而不需要遍历完整棵二叉树。同样的,代码和二叉树的中序遍历很像,可以对比来看
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
if not pRoot:
return None
node = self.KthNode(pRoot.left, k)
if node:
return node
self.count += 1
if self.count == k:
return pRoot
node = self.KthNode(pRoot.right, k)
if node:
return node
【剑指offer-Python3】63. 数据流中的中位数
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
# -*- coding:utf-8 -*-
class Solution:
def __init__():
self.arr = []
def Insert(self, num):
# write code here
self.arr.append(num)
self.arr.sort()
def GetMedian(self):
# write code here
length = len(self.arr)
if length %2 == 1:
return self.arr[length//2]
else:
return (self.arr[length//2] + self.arr[length//2-1])/2.0
import math
import heapq
class Solution:
nums = []
def Insert(self, num):
heapq.heappush(self.nums, num)
def GetMedian(self):
mid = math.ceil(len(self.nums)/2)
return (heapq.nlargest(mid, self.nums)[-1] + heapq.nsmallest(mid, self.nums)[-1])/2.0
【剑指offer-Python3】64. 滑动窗口的最大值
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
maxqueue = []
maxlist = []
n = len(num)
if n == 0 or size == 0 or size > n:
return maxlist
for i in range(n):
if len(maxqueue) > 0 and i - size >= maxqueue[0]:
maxqueue.pop(0)
while len(maxqueue) > 0 and num[i] > num[maxqueue[-1]]:
maxqueue.pop()
maxqueue.append(i)
if i >= size-1:
maxlist.append(num[maxqueue[0]])
return maxlist
【剑指offer-Python3】65. 矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if len(matrix) == 0 or len(matrix) != rows*cols or len(path) == 0:
return False
visited = [False] * len(matrix)
pathlength = 0
for i in range(rows):
for j in range(cols):
if self.isPositionInPath( matrix, rows, cols, path, j, i, visited, pathlength):
return True
return False
def isPositionInPath(self, matrix, rows, cols, path, x, y, visited, pathlength):
if len(path) == pathlength[0]:
return True
cushpath = False
if 0<= x < cols and 0<= y < rows and matrix[y*cols+x] == path[pathlength[0]] \
and not visited[y*cols+x]:
visited[y*cols+x] = True
pathlength[0] += 1
cushpath = self.isPositionInPath(matrix, rows, cols, x-1, y, visited, pathlength) \
or self.isPositionInPath(matrix, rows, cols, x, y-1, visited, pathlength) \
or self.isPositionInPath(matrix, rows, cols, x+1, y, visited, pathlength) \
or self.isPositionInPath(matrix, rows, cols, x, y+1, visited, pathlength)
if not cushpath:
pathlength[0] -= 1
visited[y*cols+x] = False
return cushpath
【剑指offer-Python3】66. 机器人的运动范围
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if rows < 1 or cols < 1 or treshold < 0:
return 0
visited = [False] *(rows*cols)
return self.moving(threshold, rows, cols, 0, 0, visited)
def moving(threshold, rows, cols, curx, cury, visited):
cnt = 0
if 0<= curx < cols and 0<= cury<rows and not visited[cury*cols+curx]:
if self.calibrateSum(curx) + self.calibrateSum(cury) < threshold:
visited[cury*cols+curx] = True
cnt = 1 + self.moving(threshold, rows, cols, curx-1, cury, visited) \
+ self.moving(threshold, rows, cols, curx, cury-1, visited) \
+ self.moving(threshold, rows, cols, curx+1, cury, visited) \
+ self.moving(threshold, rows, cols, curx, cury+1, visited)
return cnt
def calibrateSum(self, x):
ressum = 0
while x != 0:
ressum += x%10
x = x/10
return ressum