构建乘积数组
给定一个数组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]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)
思路:题目要求B的第i个元素等于A中除了第i个元素所以元素乘积。,双层循环,i==j跳过即可。
class Solution:
def multiply(self, A):
# write code here
la=len(A)
B=[1]*la #B=[1, 1, 1, 1, 1]
for i in range(len(B)):
b=1
for j in range(la):
if i==j:
continue
b*=A[j]
pass
B[i]=b
return B
pass
pass
# 实例化对象
data=Solution()
a=data.multiply([1,2,3,4,5])
print(a)
不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
# -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
s=[]
s.append(num1)
s.append(num2)
return '{}和{}的和是{}'.format(num1,num2,sum(s))
pass
pass
Sum=Solution()
print(Sum.Add(2,5))
变态跳台阶(贪心算法)
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:
0级有0种方法
1级有1种方法
2级有2种 【2,(1,1)】
3级有4种 【3,(2,1),(1,2),(1,1,1)】
4级有8种 【4,(3,1),(1,3),(2,2),(2,1,1),(1,1,2),(1,2,1),(1,1,1,1)】
。。。
观察,后一级都是上一级的2倍,故2*f(n-1),将特殊的两级拿出来即可。
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self,number):
# write code here
if number == 1:
return 1
elif number==0:
return 0
else:
return 2*self.jumpFloorII(number-1)
pass
pass
pass
qw=Solution()
c=qw.jumpFloorII(5)
print(c)
用两个栈来实现一个队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。(push()是用来在数组末端添加项,并且返回添加后数组的长度;pop()在数组末端移除项,返回移除的数组元素;)(列表中append在后面添加数,pop从后面删除数)
解题思路:栈是先进后出,队列是先进先出,有两个栈:栈1,栈2,可以先把栈1的元素弹出放入到栈2中,然后在弹出栈2的元素,这样就实现了先进先出。如: 依次输入到栈1的元素为a,b,c;栈1从顶到底:c,b,a;栈1弹出的元素放入栈2中,则栈2从顶到底为:a,b,c;实现了队列的先进先出
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
# 初始化定义两个空列表作为栈
self.stack1=[]
self.stack2=[]
def push(self, node):
'''
入栈
:param node:入栈的数
:return:stack1=[node1,node2,node3.....]
'''
# write code here
self.stack1.append(node)
def pop(self):
# return xx
'''
出栈
:return:
'''
while self.stack1: # 将1中的元素全部倒着出来,并填入2中
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
pass
pass
z=Solution()
z.push('a')
z.push('b')
z.push('c')
z.push('d')
print(z.pop())
print(z.pop())
print(z.pop())
print(z.pop())
二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
class Solution:
def TreeDepth(self, pRoot):
# write code here
# 使用层次遍历,当树为空直接返回0
if pRoot is None:
return 0
# 使用递归
# 如果该树只有一个结点,它的深度为1.如果根节点只有左子树没有右子树,
# 那么树的深度为左子树的深度加1;同样,如果只有右子树没有左子树,
# 那么树的深度为右子树的深度加1。如果既有左子树也有右子树,
# 那该树的深度就是左子树和右子树的最大值加1.
count = max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
return count
pass
pass
二叉树的镜像
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if root != None:
root.left,root.right = root.right,root.left
self.Mirror(root.left)
self.Mirror(root.right)