一个小时,两道算法题
第一题:列表加和
给定一个int类型的列表(如[1, 9, 8, 8])和一个加和元素(如34),计算列表元素所组成的数字(1988)与加和元素相加后的结果(1988+34=2022,此处仅作为讲解示例,实际操作中不允许这样执行),并以列表的形式输出([2, 0, 2, 2])。
要求:
必须是在列表状态下进行操作,不能将列表中的元素重组为一个整数(如1988)与加和元素进行计算。
示例:
[1, 9, 8, 8] + 34 -> [2, 0, 2, 2]
[2, 7, 3, 9] + 25798 -> [2, 8, 5, 3, 7]
解题思路:
将加和元素拆分成列表,然后从后往前,按照加法计算公式,与列表中的元素对应相加,若大于等于10则进1,并将大于10的部分存储在结果列表中。
最后,将结果列表逆序输出即可。代码如下
def calc(ans, ads):
ads = list(map(int, str(ads)))
rst = []
nums_ans = len(ans)
nums_ads = len(ads)
r = 0
index_ans = nums_ans - 1
index_ads = nums_ads - 1
while index_ads >= 0 and index_ans >= 0:
temp = ans[index_ans] + ads[index_ads] + r
if temp >= 10:
rst.append(temp % 10)
r = 1
else:
rst.append(temp)
r = 0
index_ans -= 1
index_ads -= 1
for j in range(index_ans, -1, -1):
temp = ans[j] + r
if temp >= 10:
rst.append(temp % 10)
r = 1
else:
rst.append(temp)
r = 0
for j in range(index_ads, -1, -1):
temp = ads[j] + r
if temp >= 10:
rst.append(temp % 10)
r = 1
else:
rst.append(temp)
r = 0
return rst[::-1]
pass
if __name__ == '__main__':
ans = [1, 9, 8, 8]
ads = 3402
rst = calc(ans, ads)
print(rst)
pass
第二题:求树的直径
给定一棵二叉树,请找出其最长路径,并输出路径上的边的数量。
如下所示,第一棵树的最长路径为4-2-1-3,长度为3。第二棵树的最长路径为8-6-4-2-5-7-9,长度为6。
解题思路:
遍历所有父节点,统计其左右孩子的数量,并相加,即为该父节点对应的路径长度。依次递归调用即可。
其中需要注意的是,每一次遍历子节点,返回数值给父节点的时候,需要加1(对于父节点而言,当前节点本身也是其父节点的一个子节点);并且,因为是统计路径,所以对于同时含有左右子节点的节点,要返回左右子节点中的最长路径,而不是该节点所包含的路径。
代码如下:
class Node:
def __init__(self, left=None, right=None, val=None):
self.val = val
self.left = left
self.right = right
pass
def find(root):
if root is None:
rst[root] = 0
return 0
if root.left is None and root.right is None:
rst[root] = 0
return 1
count_left = find(root.left)
count_right = find(root.right)
count = count_left + count_right
# print('count = ', count)
rst[root] = count
# +1,是因为要加上作为父节点的子节点的自己
if count_right != 0 and count_left != 0:
# 对于父节点而言,统计最长路径只需要左右子树的最长路径即可
return max(count_left, count_right) + 1
else:
return count+1 # 若某个子树为None,则直接返回非None子树的路径长度
pass
def buildTree():
left = Node(val=4)
right = Node(val=5)
root = Node(left, right, 2)
right = Node(val=3)
root = Node(root, right, val=1)
return root
pass
def buildTree2():
left = Node(val=8)
root = Node(left, val=6)
left = Node(root, val=4)
right = Node(val=9)
right = Node(left=right, val=7)
right = Node(right=right, val=5)
root = Node(left, right, val=2)
right = Node(val=3)
root = Node(left=root, right=right, val=1)
return root
pass
if __name__ == '__main__':
root = buildTree()
# root = buildTree2()
rst = {}
find(root)
cnt_max = 0
for ky in rst.keys():
if ky is None:
continue
val = rst[ky]
if cnt_max < val:
cnt_max = val
# print('key:{}, val:{}'.format(ky.val, val))
print('count_max:', cnt_max)
pass
以上,即是今天面试的算法题目,不难,只是自己不够娴熟,凉凉了?