根据kyrie同学的字节跳动提前批-算法-笔试面经中的三道题给出自己的解法
第一题:
输入说明:
第一行输入n代表队伍中的人数
第二行输入队伍中每个人的身高(用空格隔开)
比如输入:
5
2 3 1 5 4
6
5 4 1 6 8 2
输出说明:
如果现在所在位置之前没有比自己身高高的,数值变为-1,如果现在所在位置之前有比自己身高高的,数值变为所在位置之前那个离自己最近的且比自己高的那个人的身高
上例的输入对应输出:
5
-1 -1 3 -1 4
6
-1 5 4 -1 -1 8
思路:题目中输入5, 2 3 1 5 4
输出应该是-1 -1 3 -1 5
. 用max_height
变量存储个体所在位置之前最高的高度,比最高的高度高则在结果中加上-1. 否则,则从前面的高度中找到离自己最近的且比自己高的那个人的身高
Time complexity: O(nm), n is the number of people, m is the distance from person i to the closest person who is taller than him. In worst case, e.g. 10,1,2,3,4,5 O(n^2).
Space complexity: O(1)
def replace_height(num, heights):
if num == 0: return [0]
if num == 1: return [-1]
res = []
max_height = 0 #2 3 5
for i, height in enumerate(heights):
if height > max_height:
res.append(-1)
max_height = height
else:
k =