剑指offer(python)(未完)

  尽量不用python特有的能够一步到位的函数,答案均已在牛客网中提交通过。

 

  1.数组:二维数组中的查找

  2.字符串:替换空格

  3.链表:从尾到头打印链表

  4.树:重建二叉树

  5.栈和队列:用两个栈实现队列

  6.查找和排序:旋转数组的最小数字

  7.递归和循环:斐波那契数列

  8.递归和循环:跳台阶

  9.递归和循环:变态跳台阶

  10.递归和循环:矩形覆盖

  11.代码的完整性:数值的整数次方

  12.代码的完整性:调整数组顺序使奇数位于偶数前面

  13.代码的鲁棒性:链表中倒数第k个结点

  14.代码的鲁棒性:反转链表

  15.代码的鲁棒性:合并两个排序的列表

  16.代码的鲁棒性:树的子结构

  17.面试思路:二叉树的镜像

  18.画图让抽象形象化:顺时针打印矩阵

  19.举例让抽象具体化:包含min函数的栈

  20.举例让抽象具体化:从上往下打印二叉树

 


 

1.数组:二维数组中的查找

 1 '''
 2 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
 3 '''
 4 class Solution:
 5     # array 二维列表
 6     def Find(self, target, array):
 7         row = len(array)
 8         col = len(array[0])
 9         
10         #从右上角开始,比target大则往左寻找,比target小则往下寻找
11         index_row = 0
12         index_col = col - 1
13         while index_row < row and index_col >= 0:
14             if array[index_row][index_col] == target:
15                 return True
16             elif array[index_row][index_col] > target:
17                 index_col -= 1
18             else:
19                 index_row += 1
20         return False
View Code

2.字符串:替换空格

 1 '''
 2 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
 3 '''
 4 class Solution:
 5     # s 源字符串
 6     def replaceSpace(self, s):
 7         space_num = s.count(' ')
 8         lenth = len(s)
 9         L = []
10         i = 0
11         
12         while i < lenth:
13             if s[i] != ' ':
14                 L.append(s[i])
15             else:
16                 L.append('%20')
17             i += 1
18         s = ''.join(L)
19         return s
View Code

3.链表:从尾到头打印链表

 1 '''
 2 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 3 '''
 4 # class ListNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.next = None
 8 
 9 class Solution:
10     # 返回从尾部到头部的列表值序列,例如[1,2,3]
11     def printListFromTailToHead(self, listNode):
12         L = []
13         while listNode != None:
14             L.append(listNode.val)
15             listNode = listNode.next
16         return L[::-1]
View Code

4.树:重建二叉树

 1 '''
 2 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 3 '''
 4 # class TreeNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.left = None
 8 #         self.right = None
 9 class Solution:
10     # 返回构造的TreeNode根节点
11     def reConstructBinaryTree(self, pre, tin):
12         if not pre or not tin:
13             return None
14         root = TreeNode(pre[0])
15         index = tin.index(pre[0])
16         #中序遍历
17         root.left = self.reConstructBinaryTree(pre[1:index + 1], tin[:index])
18         root.right = self.reConstructBinaryTree(pre[index + 1:],tin[index + 1:])
19         return root
View Code

5.栈和队列:用两个栈实现队列

 1 '''
 2 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 3 '''
 4 class Solution:
 5     def __init__(self):
 6         self.stackA = []
 7         self.stackB = []
 8     def push(self, node):
 9         self.stackA.append(node)
10     def pop(self):
11         #如果栈B为空
12         if not self.stackB:
13             while self.stackA:
14                 temp = self.stackA.pop()
15                 self.stackB.append(temp)
16             front = self.stackB.pop()
17         #如果栈B不空
18         else:
19             front = self.stackB.pop()
20         return front
View Code

6.查找和排序:旋转数组的最小数字

 1 '''
 2 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
 3 '''
 4 class Solution:
 5     def minNumberInRotateArray(self, rotateArray):
 6         if not rotateArray:
 7             return 0
 8         i = 0
 9         while (i + 1) < len(rotateArray):
10             if rotateArray[i] > rotateArray[i + 1]:
11                 return rotateArray[i + 1]
12             i += 1
13         return rotateArray[0]
View Code

7.递归和循环:斐波那契数列

 1 '''
 2 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
 3 n<=39
 4 '''
 5 class Solution:
 6     def Fibonacci(self, n):
 7         if n == 0:
 8             return 0
 9         if n == 1:
10             return 1
11         fn, fn1 = 0, 1
12         time = n - 1
13         while time > 0:
14             fn, fn1 = fn1, fn + fn1
15             time -= 1
16         return fn1
View Code

8.递归和循环:跳台阶

 1 '''
 2 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
 3 '''
 4 class Solution:
 5     def jumpFloor(self, number):
 6         if number == 1 or number == 2:
 7             return number
 8         fir = 1
 9         sec = 2
10         while (number - 2) > 0:
11             number -= 1
12             fir, sec = sec, fir + sec
13         return sec
View Code

9.递归和循环:变态跳台阶

1 '''
2 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
3 '''
4 class Solution:
5     def jumpFloorII(self, number):
6         return 2 ** (number - 1)
View Code

10.递归和循环:矩形覆盖

 1 '''
 2 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
 3 '''
 4 class Solution:
 5     def rectCover(self, number):
 6         if number == 0 or number == 1 or number == 2:
 7             return number
 8         fir = 1
 9         sec = 2
10         while (number - 2) > 0:
11             number -= 1
12             fir, sec = sec, fir + sec
13         return sec
View Code

11.代码的完整性:数值的整数次方

1 '''
2 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
3 '''
4 class Solution:
5     def Power(self, base, exponent):
6         return base ** exponent
View Code

12.代码的完整性:调整数组顺序使奇数位于偶数前面

 1 '''
 2 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
 3 '''
 4 class Solution:
 5     def reOrderArray(self, array):
 6         odd = []
 7         even = []
 8         while array:
 9             temp = array.pop()
10             if temp % 2 != 0:
11                 odd.append(temp)
12             else:
13                 even.append(temp)
14         while odd:
15             temp = odd.pop()
16             array.append(temp)
17         while even:
18             temp = even.pop()
19             array.append(temp)
20         return array
View Code

13.代码的鲁棒性:链表中倒数第k个结点

 1 '''
 2 输入一个链表,输出该链表中倒数第k个结点。
 3 '''
 4 class Solution:
 5     def FindKthToTail(self, head, k):
 6         if not head or k == 0:
 7             return None
 8         front = head
 9         rear = head
10         while (k - 1) > 0:
11             rear = rear.next
12             if not rear:
13                 return None
14             k -= 1
15         while rear.next:
16             front = front.next
17             rear = rear.next
18         return front
View Code

14.代码的鲁棒性:反转链表

 1 '''
 2 输入一个链表,反转链表后,输出新链表的表头。
 3 '''
 4 # class ListNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.next = None
 8 class Solution:
 9     # 返回ListNode
10     def ReverseList(self, pHead):
11         if not pHead or not pHead.next:
12             return pHead
13         #头插法
14         rear = pHead
15         head = pHead.next
16         cur = head.next
17         rear.next = None
18         head.next = rear
19         while cur:
20             temp = cur.next
21             cur.next = head
22             head = cur
23             cur = temp
24         return head
View Code

15.代码的鲁棒性:合并两个排序的列表

 1 '''
 2 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 3 '''
 4 # class ListNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.next = None
 8 class Solution:
 9     # 返回合并后列表
10     def Merge(self, pHead1, pHead2):
11         if not pHead1:
12             return pHead2
13         if not pHead2:
14             return pHead1
15         if pHead1.val <= pHead2.val:
16             head, rear = pHead1, pHead1
17             pHead1 = pHead1.next
18         else:
19             head, rear = pHead2, pHead2
20             pHead2 = pHead2.next
21         while pHead1 and pHead2:
22             if pHead1.val <= pHead2.val:
23                 rear.next = pHead1
24                 rear = rear.next
25                 pHead1 = pHead1.next
26             else:
27                 rear.next = pHead2
28                 rear = rear.next
29                 pHead2 = pHead2.next
30         if pHead1:
31             rear.next = pHead1
32         else:
33             rear.next = pHead2
34         return head
View Code

16.代码的鲁棒性:树的子结构

 1 '''
 2 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
 3 '''
 4 # class TreeNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.left = None
 8 #         self.right = None
 9 class Solution:
10     def HasSubtree(self, pRoot1, pRoot2):
11         result = False
12         if pRoot1 and pRoot2:
13             #先序遍历,找到pRoot2在pRoot1中的根结点
14             if pRoot1.val == pRoot2.val:
15                 result = self.IsSubTree(pRoot1, pRoot2)
16             if not result:
17                 result = self.IsSubTree(pRoot1.left, pRoot2)
18             if not result:
19                 result = self.IsSubTree(pRoot1.right, pRoot2)
20         return result
21     
22     def IsSubTree(self, root1, root2):
23         if not root2:
24             return True
25         if not root1:
26             return False
27         if root1.val != root2.val:
28             return False
29         return self.IsSubTree(root1.left, root2.left) and self.IsSubTree(root1.right, root2.right)
View Code

17.面试思路:二叉树的镜像

 1 '''
 2 操作给定的二叉树,将其变换为源二叉树的镜像。
 3 '''
 4 # class TreeNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.left = None
 8 #         self.right = None
 9 class Solution:
10     # 返回镜像树的根节点
11     def Mirror(self, root):
12         if not root:
13             return root
14         root.left, root.right = root.right, root.left
15         self.Mirror(root.left)
16         self.Mirror(root.right)
View Code

18.画图让抽象形象化:顺时针打印矩阵

 1 '''
 2 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
 3 '''
 4 class Solution:
 5     # matrix类型为二维列表,需要返回列表
 6     def printMatrix(self, matrix):
 7         res = []
 8         while matrix:
 9             #左->右
10             res += matrix.pop(0)
11             if matrix and matrix[0]:
12                 #上->下
13                 for row in matrix:
14                     res.append(row.pop())
15             #右->左
16             if matrix:
17                 res += matrix.pop()[::-1]
18             #下->上
19             if matrix and matrix[0]:
20                 for row in matrix[::-1]:
21                     res.append(row.pop(0))
22         return res
23 #如剩下3x1矩阵,并在with循环中阻隔pop元素,则列表会变为3x1的矩阵,其中元素变为None
View Code

19.举例让抽象具体化:包含min函数的栈

 1 '''
 2 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
 3 '''
 4 class Solution:
 5     def __init__(self):
 6         self.stack = []
 7     def push(self, node):
 8         self.stack.append(node)
 9     def pop(self):
10         return self.stack.pop()
11     def top(self):
12         return self.stack(-1)
13     def min(self):
14         return min(self.stack)
View Code

20.举例让抽象具体化:从上往下打印二叉树

 1 '''
 2 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 3 '''
 4 # class TreeNode:
 5 #     def __init__(self, x):
 6 #         self.val = x
 7 #         self.left = None
 8 #         self.right = None
 9 class Solution:
10     # 返回从上到下每个节点值列表,例:[1,2,3]
11     def PrintFromTopToBottom(self, root):
12         if not root:
13             return []
14         queue = [root]
15         list = []
16         #非递归层次遍历
17         while queue:
18             temp = queue.pop(0)
19             list.append(temp.val)
20             if temp.left:
21                 queue.append(temp.left)
22             if temp.right:
23                 queue.append(temp.right)
24         return list
View Code

 

 

...

posted on 2019-06-11 12:43  一粒蜗牛  阅读(361)  评论(0)    收藏  举报

导航