给定一个不含有重复值的数组 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
function solution(n, nums) { // 初始化结果数组和单调栈 const res = new Array(n), stack = [] let popIndex, leftLessIndex // 遍历给定的数组 // 因为结果是求数组中每个位置的左右较小的位置,所以单调栈从顶向下应该是递减的 for (let i = 0; i < n; i++) { // 违反单调栈的结构时,需要弹出栈顶,并且将当前位置压入 while (stack.length && nums[stack[stack.length - 1]] > parseInt(nums[i])) { popIndex = stack.pop() leftLessIndex = stack.length ? stack[stack.length - 1] : -1 res[popIndex] = [leftLessIndex, i] } stack.push(i) } // 栈中还有元素,说明即使遍历完数组也没有比栈中剩余的元素小的元素,所以其右边没有比栈中剩余元素小的元素 while (stack.length) { popIndex = stack.pop() leftLessIndex = stack.length ? stack[stack.length - 1] : -1 res[popIndex] = [leftLessIndex, -1] } return res } let n = parseInt(readline()) let nums = readline().split(' ') let result = solution(n, nums) for (let i = 0; i < n; i++) { print(result[i][0] + ' ' + result[i][1]) }