给定一个不含有重复值的数组 arr,找到每一个 i 位置左边和右边离 i 位置最近且值比 arr[i] 小的位置。返回所有位置相应的信息。
第一行输入一个数字 n,表示数组 arr 的长度。
以下一行输出 n个数字,表示数组的值。
输出n行,每行两个数字 L 和 R,如果不存在,则值为-1,下标从0开始。
7 3 4 1 5 6 2 7
-1 2 0 2 -1 -1 2 5 3 5 2 -1 5 -1
n = int(input()) arr = list(map(int, input().split(' '))) res = [0]*n stack = [] for i in range(n): while stack and arr[stack[-1]]>arr[i]: pop_index = stack.pop() if stack: left_less_index = stack[-1] else: left_less_index = -1 res[pop_index] = [left_less_index, i] stack.append(i) while stack: pop_index = stack.pop() if stack: left_less_index = stack[-1] else: left_less_index = -1 res[pop_index] = [left_less_index, -1] for j in res: print(str(j[0]) + ' ' + str(j[1]))